René's URL Explorer Experiment


Title: Bug: RuntimeError during cleanup on Windows – no running event loop · Issue #575 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Bug: RuntimeError during cleanup on Windows – no running event loop · Issue #575 · modelcontextprotocol/python-sdk

X Title: Bug: RuntimeError during cleanup on Windows – no running event loop · Issue #575 · modelcontextprotocol/python-sdk

Description: Describe the bug When running the mcp client using uv run client.py on Windows, the client connects and runs correctly, but after the response is returned, a RuntimeError: no running event loop is thrown during shutdown. The error occurs...

Open Graph Description: Describe the bug When running the mcp client using uv run client.py on Windows, the client connects and runs correctly, but after the response is returned, a RuntimeError: no running event loop is ...

X Description: Describe the bug When running the mcp client using uv run client.py on Windows, the client connects and runs correctly, but after the response is returned, a RuntimeError: no running event loop is ...

Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/575

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Bug: RuntimeError during cleanup on Windows – no running event loop","articleBody":"---\n\n### **Describe the bug**  \nWhen running the `mcp` client using `uv run client.py` on **Windows**, the client connects and runs correctly, but after the response is returned, a `RuntimeError: no running event loop` is thrown during shutdown. The error occurs inside the `terminate_windows_process` function in `win32.py`, which uses `anyio.fail_after()` after the event loop has already closed.\n\n---\n\n### **To Reproduce**\nSteps to reproduce the behavior:\n1. Use the following Python code to create a minimal MCP client that connects to a server and runs a tool-enabled Groq chat query:\n\n```python\n# save this as `client.py`\nimport asyncio\nimport json\nfrom contextlib import AsyncExitStack\nimport os\nfrom typing import Any, Dict, List, Optional\n\nimport nest_asyncio\nfrom dotenv import load_dotenv\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\nfrom groq import AsyncGroq\n\nnest_asyncio.apply()\nload_dotenv()\n\nclass MCPGroqClient:\n    def __init__(self, model: str = \"llama-3.3-70b-versatile\"):\n        self.session: Optional[ClientSession] = None\n        self.exit_stack = AsyncExitStack()\n        self.groq_client = AsyncGroq(api_key=os.getenv(\"GROQ_API_KEY\"))\n        self.model = model\n        self.stdio: Optional[Any] = None\n        self.write: Optional[Any] = None\n\n    async def connect_to_server(self, server_script_path: str = \"server.py\"):\n        server_params = StdioServerParameters(command=\"python\", args=[server_script_path])\n        stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))\n        self.stdio, self.write = stdio_transport\n        self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))\n        await self.session.initialize()\n        tools_result = await self.session.list_tools()\n        print(\"\\nConnected to server with tools:\")\n        for tool in tools_result.tools:\n            print(f\"  - {tool.name}: {tool.description}\")\n\n    async def get_mcp_tools(self) -\u003e List[Dict[str, Any]]:\n        tools_result = await self.session.list_tools()\n        return [\n            {\n                \"type\": \"function\",\n                \"function\": {\n                    \"name\": tool.name,\n                    \"description\": tool.description,\n                    \"parameters\": tool.inputSchema,\n                },\n            }\n            for tool in tools_result.tools\n        ]\n\n    async def process_query(self, query: str) -\u003e str:\n        tools = await self.get_mcp_tools()\n        response = await self.groq_client.chat.completions.create(\n            model=self.model,\n            messages=[{\"role\": \"user\", \"content\": query}],\n            tools=tools,\n            tool_choice=\"auto\",\n        )\n        assistant_message = response.choices[0].message\n        messages = [{\"role\": \"user\", \"content\": query}, assistant_message]\n\n        if assistant_message.tool_calls:\n            for tool_call in assistant_message.tool_calls:\n                result = await self.session.call_tool(\n                    tool_call.function.name,\n                    arguments=json.loads(tool_call.function.arguments),\n                )\n                messages.append({\n                    \"role\": \"tool\",\n                    \"tool_call_id\": tool_call.id,\n                    \"content\": result.content[0].text,\n                })\n\n            final_response = await self.groq_client.chat.completions.create(\n                model=self.model,\n                messages=messages,\n                tools=tools,\n                tool_choice=\"none\",\n            )\n            return final_response.choices[0].message.content\n\n        return assistant_message.content\n\n    async def cleanup(self):\n        await self.exit_stack.aclose()\n\nasync def main():\n    client = MCPGroqClient()\n    await client.connect_to_server()\n    query = \"What is our company's vacation policy?\"\n    print(f\"\\nQuery: {query}\")\n    response = await client.process_query(query)\n    print(f\"\\nResponse: {response}\")\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n2. Set your environment variable `GROQ_API_KEY`.\n3. Start the server with a valid tool (like `knowledge_base`).\n4. Run the client using:\n   ```bash\n   uv run client.py\n   ```\n5. Observe the traceback at shutdown related to `RuntimeError: no running event loop`.\n\n---\n\n### **Expected behavior**  \nThe client should shut down gracefully **without throwing exceptions** after processing a response.\n\n---\n\n### **Screenshots / Traceback**\n```bash\nException ignored in: \u003casync_generator object stdio_client at 0x000002025AE0EFC0\u003e\nTraceback (most recent call last):\n  File \"C:\\Program Files\\Python312\\Lib\\asyncio\\tasks.py\", line 314, in __step_run_and_handle_result\n    result = coro.send(None)\n             ^^^^^^^^^^^^^^^\nRuntimeError: async generator ignored GeneratorExit\n\nException ignored in: \u003ccoroutine object terminate_windows_process at 0x000002025AF5F3E0\u003e\nTraceback (most recent call last):\n  File \"...\\Lib\\site-packages\\mcp\\client\\stdio\\win32.py\", line 105, in terminate_windows_process\n    with anyio.fail_after(2.0):\n  File \"C:\\Program Files\\Python312\\Lib\\contextlib.py\", line 158, in __exit__\n    self.gen.throw(value)\n  File \"...\\Lib\\site-packages\\anyio\\_core\\_tasks.py\", line 112, in fail_after\n    with get_async_backend().create_cancel_scope(\n  File \"...\\Lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 456, in __exit__\n    if current_task() is not self._host_task:\n       ^^^^^^^^^^^^^^\nRuntimeError: no running event loop\n```\n\n---\n\n### **Desktop (please complete the following information):**\n- **OS:** Windows 11  \n- **Python Version:** 3.12  \n- **MCP Version:** [insert version]  \n- **AnyIO Version:** [insert version]  \n- **Terminal:** Windows PowerShell  \n- **Command Used:** `uv run client.py`\n\n---\n\n### **Additional context**  \n- This issue seems to be a **Windows-specific async shutdown bug**.\n- Happens when `anyio.fail_after()` is used after the event loop is already closed.\n- Suggest adding a check before using async context tools during shutdown, such as:\n  ```python\n  if asyncio.get_event_loop().is_running():\n      with anyio.fail_after(2.0):\n          ...\n  ```\n- Or use `try/except RuntimeError` to suppress it gracefully.\n\n---\n","author":{"url":"https://github.com/Dadiya-Harsh","@type":"Person","name":"Dadiya-Harsh"},"datePublished":"2025-04-23T18:26:36.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":0},"url":"https://github.com/575/python-sdk/issues/575"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:a4c83bec-483e-56b3-c06b-1ea073cff2cd
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idE212:B6152:A347CC:EC3186:6A579807
html-safe-nonce50c2268c718f2a61631991ad89ac62b2e367b50c208a3241cba4bed256fc9092
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMjEyOkI2MTUyOkEzNDdDQzpFQzMxODY6NkE1Nzk4MDciLCJ2aXNpdG9yX2lkIjoiNjQwNjA2ODE5NjIxNTMzMDgyMyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac4d2932221a5a02df6f29c562128db8389514a8f6695b0ac4fecae26fbd21c9b1
hovercard-subject-tagissue:3014919425
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/575/issue_layout
twitter:imagehttps://opengraph.githubassets.com/b11fef2af559d9dfd5d7ba21c044200cab8d74fa047b58edc9db2a9e37c5d1c8/modelcontextprotocol/python-sdk/issues/575
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/b11fef2af559d9dfd5d7ba21c044200cab8d74fa047b58edc9db2a9e37c5d1c8/modelcontextprotocol/python-sdk/issues/575
og:image:altDescribe the bug When running the mcp client using uv run client.py on Windows, the client connects and runs correctly, but after the response is returned, a RuntimeError: no running event loop is ...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameDadiya-Harsh
hostnamegithub.com
expected-hostnamegithub.com
Nonea87fc68e9bdf22e1c7e48ac6a60b98882f4bb103314b3f26b3460c61fc5441ae
turbo-cache-controlno-preview
go-importgithub.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git
octolytics-dimension-user_id182288589
octolytics-dimension-user_loginmodelcontextprotocol
octolytics-dimension-repository_id862584018
octolytics-dimension-repository_nwomodelcontextprotocol/python-sdk
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id862584018
octolytics-dimension-repository_network_root_nwomodelcontextprotocol/python-sdk
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releasea2198d0212ed703af207673eb4d0868d4f867a5b
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/575#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F575
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F575
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=modelcontextprotocol%2Fpython-sdk
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/575
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/575
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/575
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/575
modelcontextprotocol https://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Notifications https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Fork 3.6k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Star 23.6k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Code https://github.com/modelcontextprotocol/python-sdk
Issues 251 https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests 289 https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality 6 https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
Code https://github.com/modelcontextprotocol/python-sdk
Issues https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
Bug: RuntimeError during cleanup on Windows – no running event loophttps://github.com/modelcontextprotocol/python-sdk/issues/575#top
https://github.com/Dadiya-Harsh
Dadiya-Harshhttps://github.com/Dadiya-Harsh
on Apr 23, 2025https://github.com/modelcontextprotocol/python-sdk/issues/575#issue-3014919425
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.