modelcontextprotocol / modelcontextprotocol/python-sdk

How can I manage resource across multiple tool calls during one session?

Open
#3,549 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
24.3k
Forks
4k
Avg merge
1d 1h
Merged PRs (30d)
31

Description

Description

I was messing around multiple agents running in parallel, and suffered from some kind of race condition. I had to write a lock for them.

It looks like each agent has their own session, but I don't have any idea to handle how they create and terminate.

The code can be like below, assuming it is a streamable-http app:

import asyncio

import mcp
from mcp.server.fastmthemcp import Context
import mcp.events # some mcp protocol events, maybe session creation or termination.

mcp_server = mcp.server.FastMCP("demo-locking")
lock = None

async def acquire_lock(ctx: Context):
    # assume ctx.session.session_id = mcp-session-id acquired from headers, however not defined in this field.
    while lock is not None and lock != ctx.session.session_id:
        await asyncio.sleep(1)
        ctx.info("Waiting for the lock")
    lock = ctx.session.session_id


@mcp_server.tool()
async def tool1(ctx: Context):
    await acquire_lock(ctx)
    # ... do tool things

@mcp_server.tool()
async def tool2(ctx: Context):
    await acquire_lock(ctx)
    # ... do tool things

async def release_lock(ctx: Context):
    if lock == ctx.session.session_id:
        lock = None

mcp_server.add_handler(mcp.events.SESSION_TERMINATE, release_lock) # should be something like this to register a session cleanup.

app = mcp_server.streamable_http_app()

import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
References

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the streamable_http_app() entry point and the Context/session references in the example, then inspect how add_handler() and SESSION_TERMINATE are currently defined. The issue does not identify existing files or tests. Done would require a decided, documented approach for coordinating resources across tool calls and handling session cleanup.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Active
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.