Title: Refactor global contextvars request context into explicit parameters · Issue #1684 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Refactor global contextvars request context into explicit parameters · Issue #1684 · modelcontextprotocol/python-sdk
X Title: Refactor global contextvars request context into explicit parameters · Issue #1684 · modelcontextprotocol/python-sdk
Description: Description Summary The Python SDK currently uses a global contextvars.ContextVar (e.g. request_ctx) to hold per-request state for the server. This enables convenience helpers like get_request_context(), but it also introduces implicit d...
Open Graph Description: Description Summary The Python SDK currently uses a global contextvars.ContextVar (e.g. request_ctx) to hold per-request state for the server. This enables convenience helpers like get_request_cont...
X Description: Description Summary The Python SDK currently uses a global contextvars.ContextVar (e.g. request_ctx) to hold per-request state for the server. This enables convenience helpers like get_request_cont...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/1684
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Refactor global contextvars request context into explicit parameters","articleBody":"### Description\n\n## Summary\n\nThe Python SDK currently uses a global `contextvars.ContextVar` (e.g. `request_ctx`) to hold per-request state for the server. This enables convenience helpers like `get_request_context()`, but it also introduces implicit dependencies and makes testing, debugging, and refactoring harder.\n\nThis proposal suggests moving towards **explicit context passing** in handlers and eventually **deprecating global request context access**, with a migration path.\n\n## Background\n\nToday, the low-level server and FastMCP rely on a global `ContextVar` that holds a `RequestContext`. Handler code can implicitly call `get_request_context()` without any indication in the function signature that it depends on request-local state.\n\nThis has several drawbacks:\n\n- **Hidden dependencies:** Functions depend on ambient state, not their parameters.\n- **Debugging complexity:** Stack traces do not show where the context came from.\n- **Testability:** Unit tests must set up `ContextVar` state or fall back to full integration tests.\n- **Refactoring risk:** Moving code between modules can silently break if context assumptions change.\n\n## Proposal\n\n### Phase 1 – Explicit context in handler signatures\n\n1. Make `RequestContext` (or a higher-level `Context`) an **explicit parameter** for all tool/resource handlers at the low-level server boundary.\n2. At the FastMCP layer, inject the context explicitly into handler callsites instead of relying on global `ContextVar` lookups.\n3. Keep `get_request_context()` for now, but document it as **deprecated** and implemented in terms of the explicit parameter passing.\n\n### Phase 2 – Internal-only use (or removal) of `ContextVar`\n\n4. Refactor internal call chains so that the `RequestContext` is always passed as an argument rather than read from a global.\n5. Limit any remaining `ContextVar` usage to:\n - bridging with external frameworks (if needed), or\n - cross-cutting concerns like tracing where explicit parameter threading is impossible.\n6. Remove `get_request_context()` (or keep only as a thin, clearly discouraged compatibility helper).\n\n### Migration and compatibility\n\n- Provide an explicit, documented pattern for handlers that need context:\n - e.g. `async def tool(ctx: Context, ...) -\u003e ...`\n- Keep the current behavior working for at least one minor release, with deprecation warnings where appropriate.\n- Update examples and docs to promote explicit context usage.\n\n## Why this matters\n\n- **Testability:** Handlers become pure-ish functions with explicit dependencies.\n- **Debugging:** It’s easier to follow how context flows through the system.\n- **Robustness:** Less risk of accidental context leakage across concurrent requests.\n- **API clarity:** Users see, in signatures, that a handler depends on request context.\n\n## Acceptance criteria\n\n- [ ] All public handler registration paths can accept an explicit context parameter.\n- [ ] Core server internals pass `RequestContext` explicitly rather than relying on `ContextVar`.\n- [ ] `get_request_context()` is either deprecated or clearly documented as a compatibility shim.\n- [ ] Tests no longer need to directly manipulate global request `ContextVar` state.\n- [ ] Documentation updated to show explicit context patterns as the recommended approach.\n\n\n### References\n\n_No response_","author":{"url":"https://github.com/dgenio","@type":"Person","name":"dgenio"},"datePublished":"2025-11-28T11:52:12.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":4},"url":"https://github.com/1684/python-sdk/issues/1684"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:f5ad21ff-070e-7a7d-4fa7-82ab53086c7c |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | C436:16F405:31BB941:40E761A:6A5CE142 |
| html-safe-nonce | 7e952b66ea984964ff867944857904f91a88fa253649ccdd82e34377f3c151a8 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDNDM2OjE2RjQwNTozMUJCOTQxOjQwRTc2MUE6NkE1Q0UxNDIiLCJ2aXNpdG9yX2lkIjoiODg5MjY3MzU4ODUwNTQwMzcxNCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 1a8f0816785fda55cf9688b2a852c9d46f31e3b40b2c55172a0d65e4706bb4e3 |
| hovercard-subject-tag | issue:3674645928 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/1684/issue_layout |
| twitter:image | https://opengraph.githubassets.com/90d21c9f09ceb082327472266050d401cdd871014cf7d96291b4c557b3a0361e/modelcontextprotocol/python-sdk/issues/1684 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/90d21c9f09ceb082327472266050d401cdd871014cf7d96291b4c557b3a0361e/modelcontextprotocol/python-sdk/issues/1684 |
| og:image:alt | Description Summary The Python SDK currently uses a global contextvars.ContextVar (e.g. request_ctx) to hold per-request state for the server. This enables convenience helpers like get_request_cont... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | dgenio |
| hostname | github.com |
| expected-hostname | github.com |
| None | 5290d7e14309ad1e76106a9c4237bd1041517e83ea182c8ab756752cb0c6940b |
| turbo-cache-control | no-preview |
| go-import | github.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git |
| octolytics-dimension-user_id | 182288589 |
| octolytics-dimension-user_login | modelcontextprotocol |
| octolytics-dimension-repository_id | 862584018 |
| octolytics-dimension-repository_nwo | modelcontextprotocol/python-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 862584018 |
| octolytics-dimension-repository_network_root_nwo | modelcontextprotocol/python-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9c975978430e9ad293956f2bbdaf153b1bd84a99 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width