Skip to content

Conversation

SigureMo
Copy link
Contributor

@SigureMo SigureMo commented Apr 6, 2025

Motivation and Context

In my use case, I use PEP 563 (from __future__ import annotations) and a Context with generic parameters (i.e. Context[ServerSession, AppContext]) to annotate the Context in the tool function. But it doesn't detect Context parameters correctly. Here is a minimal reproduction:

# example.py
from __future__ import annotations

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass

from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession

mcp = FastMCP("My App")


@dataclass
class AppContext:
    magic: "int"


@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
    yield AppContext(magic=42)


mcp = FastMCP("My App", lifespan=app_lifespan)


@mcp.tool()
def get_magic(ctx: Context[ServerSession, AppContext]) -> str:
    magic = ctx.request_context.lifespan_context.magic
    return str(magic)
uv run --extra "cli" mcp dev example.py
image

So I tried to tweak the Context parameter detection logic a bit and it seems to work.

image

How Has This Been Tested?

uv run pytest tests/server/fastmcp/test_server.py

Breaking Changes

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

@SigureMo SigureMo closed this Apr 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant