How to set / get `client_id`?
I'd like to be able to retrieve the client_id from inside a tool call on an MCP server. However, it is always None. What do I need to set in the MCP client in order to be able to retrieve it on the server?
The client code is basically taken from the documentation:
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(
command="python", # Executable
args=["example_server.py"], # Optional command line arguments
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(
read, write
) as session:
# Initialize the connection
await session.initialize()
# Call a tool
result = await session.call_tool("my_tool")
The tool function is as follows:
mcp = FastMCP("docint")
@mcp.tool()
async def my_tool(ctx: Context) -> Optional[str]:
"""
Extracts client ID and request ID from the context.
Returns:
client ID and request ID from the context.
"""
return f"{ctx.client_id} {ctx.request_id}" # <----- THIS
This prints None 2 (client_id as None).
What am I missing?
Thank you.
I have the exact same question, but i think that this is a WIP feature that will be implemented based on this draft.
Can one of the contributors or maintainers confirm if this is supposed to work, please?
Or is it broken / WIP as the above comment suggests?
Thank you.
ctx.client_id isn't populated by the SDK: it just echoes a client_id key from the request's _meta (both on v2 main and the 1.x FastMCP Context), and clients don't send one by default, hence the None. To have it set, pass it per call: await session.call_tool("my_tool", meta={"client_id": "my-app"}) (the meta= argument on call_tool has been there since 1.19 and is on v2's Client/ClientSession too). If what you're actually after is an authenticated client's identity, that's the OAuth client_id on the access token: get_access_token().client_id, covered in The caller's identity.
Example (v2)
import anyio
from mcp import Client
from mcp.server.mcpserver import Context, MCPServer
mcp = MCPServer("demo")
@mcp.tool()
def my_tool(ctx: Context) -> str:
return f"client_id={ctx.client_id!r}"
async def main() -> None:
async with Client(mcp) as client:
print((await client.call_tool("my_tool")).content[0].text)
print((await client.call_tool("my_tool", meta={"client_id": "my-app"})).content[0].text)
anyio.run(main)
Prints client_id=None, then client_id='my-app'.
Closing this as part of a wider backlog cleanup around the v2 release. Feel free to reopen if this is still relevant.