Skip to content

Handle YouTube short URLs in transcript retrieval #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/mcp_youtube_transcript/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,14 @@ def get_transcript(
) -> str:
"""Retrieves the transcript of a YouTube video."""
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)

video_id = query_params.get("v", [None])[0]
if video_id is None:
raise ValueError(f"couldn't find a video ID from the provided URL: {url}.")
if parsed_url.hostname == "youtu.be":
video_id = parsed_url.path.lstrip("/")
else:
q = parse_qs(parsed_url.query).get("v")
if q is None:
raise ValueError(f"couldn't find a video ID from the provided URL: {url}.")
video_id = q[0]

if lang == "en":
languages = ["en"]
Expand Down
16 changes: 16 additions & 0 deletions tests/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,19 @@ async def test_get_transcript_invalid_url(mcp_client_session: ClientSession) ->
async def test_get_transcript_not_found(mcp_client_session: ClientSession) -> None:
res = await mcp_client_session.call_tool("get_transcript", arguments={"url": "https//www.youtube.com/watch?v=a"})
assert res.isError


@pytest.mark.skipif(os.getenv("CI") == "true", reason="Skipping this test on CI")
@pytest.mark.anyio
async def test_get_transcript_with_short_url(mcp_client_session: ClientSession) -> None:
video_id = "LPZh9BOjkQs"

expect = "\n".join((item.text for item in YouTubeTranscriptApi().fetch(video_id)))

res = await mcp_client_session.call_tool(
"get_transcript",
arguments={"url": f"https://youtu.be/{video_id}"},
)
assert isinstance(res.content[0], TextContent)
assert res.content[0].text == expect
assert not res.isError