Back to all guides
Agent Gateway

Delegated token package: carry X-IK-Token through your agents and MCP servers

Use the indykite-delegated-token Python package in an MCP server or an A2A agent behind the Agent Gateway: read the delegation token of the request being handled, and send it on to the next gateway so a multi-hop workflow is not refused.

Delegated token package: carry X-IK-Token

A user asks an AI agent to do something. That agent calls another agent, which calls a tool server, and so on. Each of them sits behind an Agent Gateway, which checks who is asking before it lets the call through.

To check, each gateway needs the whole story: which user started it, and which agents passed the request along. That story travels in the delegation token, in a header named X-IK-Token. When an agent calls the next one and does not pass the token on, the next gateway refuses the call.

indykite-delegated-token is a Python package you add to your agent or tool server. It does two jobs:

  • It catches the token when a request comes in, so your code can read it.
  • It passes the token on when your code calls the next agent or tool server, and only to a target that says it accepts it, over a secure connection.

In a tool server it is one line, install(server). In an agent it is one middleware. For the calls going out, you use the HTTP client or the interceptor that comes with the package. The rest of this guide gives the details.

What is the delegated token package?

indykite-delegated-token is a Python package for the code that runs behind an Agent Gateway: an MCP server or an A2A agent. When the gateway is configured with a Token Service, it sends the delegation token of the workflow to that server or agent in the X-IK-Token header. The package does the two things the server or agent then has to do with it:

  • Receive: make the token of the request being handled available to your code, through get_delegated_token().
  • Send on: add the token to the calls your code makes to another MCP server or A2A agent, and only to the targets that announce they accept it.

The package has no dependencies of its own. It adapts the MCP Python SDK, FastMCP and the A2A Python SDK, and the agent frameworks built on them.

When do I need it?

You need it when a server or agent behind a gateway calls another server or agent that is behind a gateway too. The next gateway reads the chain of the workflow from X-IK-Token; a call that arrives without it is refused.

Your code What to use
An MCP server whose tools only answer the callerNothing, unless a tool wants to read the token: then install(server).
An MCP server whose tools call another MCP server or an A2A agentinstall(server) and the package's client for each outbound call.
An A2A agent that calls MCP servers or other agentsDelegatedTokenASGIMiddleware and the package's client for each outbound call.
An agent built with an agent frameworkThe same, with the hook of the framework: see Agent frameworks.

The gateways must be configured with token_service: without it no gateway sends or announces the token, and the package sends nothing.

How do I install it?

Python 3.11 or later. Choose the extras for the SDKs your code uses:

pip install "indykite-delegated-token[mcp,a2a]"     # MCP Python SDK 2.x and A2A
pip install "indykite-delegated-token[fastmcp,a2a]" # FastMCP 4 and A2A
pip install "indykite-delegated-token[mcp1,a2a]"    # MCP Python SDK 1.x and A2A
Extra For Client module to import
mcpMCP Python SDK 2.xindykite_delegated_token.client.httpx2
fastmcpFastMCP 4indykite_delegated_token.client.httpx2
mcp1MCP Python SDK 1.xindykite_delegated_token.client.httpx
a2aA2A Python SDK (a2a-sdk)indykite_delegated_token.client.a2a

The two MCP client modules have the same functions. Which one to import follows the HTTP library of the MCP SDK in use: a client of the wrong one is rejected by the SDK.

How does my code receive the token?

MCP server

Call install(server) once, after creating the server. It accepts MCPServer and the low-level Server of the MCP SDK 2.x, FastMCP of FastMCP 4, and FastMCP and the low-level Server of the MCP SDK 1.x. Any other object raises TypeError.

from mcp.server.mcpserver import MCPServer
from indykite_delegated_token import get_delegated_token, install
#
server = MCPServer("my-server")
install(server)
#
@server.tool()
async def whoami() -> str:
    return "token received" if get_delegated_token() else "no token"
  • get_delegated_token() returns the token of the request being handled, or None. Two concurrent requests each see their own token, also in stateful sessions.
  • A request with more than one X-IK-Token value, as several headers or as one header joined with commas, gets no token.
  • FastMCP tools declared with task=True are not supported: they run after their request has been handled and see no token.

A2A agent

An agent built with a2a-sdk is a Starlette or FastAPI app. Add DelegatedTokenASGIMiddleware as its outermost middleware, with strip_header=True:

from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from starlette.applications import Starlette
from starlette.middleware import Middleware
from indykite_delegated_token.server.asgi import DelegatedTokenASGIMiddleware
#
app = Starlette(
    routes=[*create_agent_card_routes(card), *create_jsonrpc_routes(handler, "/")],
    middleware=[Middleware(DelegatedTokenASGIMiddleware, strip_header=True)],
)

With FastAPI: app.add_middleware(DelegatedTokenASGIMiddleware, strip_header=True). For any other ASGI app, wrap it: app = DelegatedTokenASGIMiddleware(app, strip_header=True).

  • The executor reads the token with get_delegated_token(). Each execute call sees the token of the request that sent its message, also for a follow-up message to an existing task and for streaming requests.
  • strip_header=True removes X-IK-Token from the request the app sees, so the token is reachable only through get_delegated_token() and does not end up in the request logs of a2a-sdk. It is off by default.
  • Do not set strip_header in front of an MCP server that uses install(): install() reads the header from the request and would see no token.
  • The agent card does not need to list the extension: the gateway declares it on the card it serves.

Work that leaves the request

Tasks your code starts in the same process keep the token of their request. Work handed to a queue or to another process must carry the token itself: read it with get_delegated_token() and restore it in the worker with use_token(token).

from indykite_delegated_token import get_delegated_token, use_token
#
token = get_delegated_token()      # in the request
#
def worker(token: str | None) -> None:
    with use_token(token):         # in the worker
        ...

The token can expire before such work ends; the next gateway then refuses the call.

How does my code send the token on?

Use the package's HTTP client for MCP calls and its interceptor for A2A calls. Both take the token of the request being handled; your code does not pass it.

MCP, SDK 2.x

from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamable_http_client
from indykite_delegated_token.client.httpx2 import http_client
#
@server.tool()
async def call_target() -> str:
    async with (
        http_client() as client,
        streamable_http_client(TARGET_MCP_URL, http_client=client) as (read, write),
        ClientSession(read, write) as session,
    ):
        await session.initialize()
        result = await session.call_tool("some_tool", {})
    ...

MCP, FastMCP 4

from fastmcp.client.transports import StreamableHttpTransport
from indykite_delegated_token.client.httpx2 import httpx_client_factory
#
transport = StreamableHttpTransport(TARGET_MCP_URL, httpx_client_factory=httpx_client_factory)

MCP, SDK 1.x

The same as for SDK 2.x, with the client.httpx module; streamable_http_client yields three values in SDK 1.x.

from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from indykite_delegated_token.client.httpx import http_client
#
@server.tool()
async def call_target() -> str:
    async with (
        http_client() as client,
        streamable_http_client(TARGET_MCP_URL, http_client=client) as (read, write, _),
        ClientSession(read, write) as session,
    ):
        await session.initialize()
        result = await session.call_tool("some_tool", {})
    ...

A2A

from a2a.client import ClientFactory
from indykite_delegated_token.client.a2a import DelegatedTokenInterceptor
#
client = ClientFactory(config).create(card, interceptors=[DelegatedTokenInterceptor()])

For an agent whose card lists the extension, the interceptor sets X-IK-Token and adds the extension to the A2A-Extensions header. Other agents get neither. The httpx client given to a2a-sdk must not follow redirects, which is its default.

Open MCP clients inside the tool call

Open the MCP client inside the tool call or request that uses it, as the examples do, and do not keep it for later calls:

  • With SDK 1.x, a client opened earlier, for example at startup, keeps the token it had then, usually none.
  • With SDK 2.x, each call carries the token of the request that made it, but the stream and the closing request of the client carry the token of the request that opened or closed it. A client reused across requests keeps sending the token of the first one.

Client settings

Setting Effect
http_client(headers=, timeout=, auth=, follow_redirects=)The arguments of the MCP SDK's own client factory, so http_client can be passed wherever an httpx_client_factory is expected. Without timeout it uses the MCP SDK's default timeouts.
http_client(transport=...)Your own transport, to configure TLS, proxies or limits. Without it the client uses the proxies of HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY; with it, only the settings of that transport.
http_client(registry=ExtensionRegistry(...))Its own record of which targets announce the extension, see the next section. ExtensionRegistry is imported from indykite_delegated_token.client.
ExtensionRegistry(allow_http=True), DelegatedTokenInterceptor(allow_http=True)Also send the token over plain http, for example to a gateway inside a private network.

The MCP clients use the Streamable HTTP transport. The legacy SSE transport is not supported.

Which targets get the token?

A request carries X-IK-Token only when there is a token and the target announced the delegated token extension. An Agent Gateway with a Token Service announces it for the server or agent it protects; your code has nothing to configure for that.

Target How it announces How the package finds out
MCP serverIts OAuth protected resource metadata (RFC 9728) has com.indykite/delegated-token in mcp_extensions, and resource is the URL of the target.Before the first request to a target, the client fetches /.well-known/oauth-protected-resource<path> on the origin of the target, without credentials.
A2A agentIts agent card lists https://indykite.com/extensions/delegated-token/v1 in capabilities.extensions.The interceptor reads the card your code gave to the A2A client.

The rules, which hold whoever set the token (the package, your code, or a header hook of a framework):

  • Transport. The token only goes over https, or over http to a loopback host (localhost, 127.0.0.0/8, ::1), unless allow_http is set.
  • Redirects. When the client follows redirects, the token only goes to the origin of the first request, or to its upgrade from http to https on the same host. A redirect to another origin, or from https to http, never gets it.
  • A token your code sets itself in X-IK-Token goes out as set, under the same rules: the header is removed from a request to a target that does not announce, to another origin after a redirect, or over plain HTTP without allow_http.
  • A 401 from a target not known to announce. When the answer carries WWW-Authenticate: Bearer resource_metadata="…" and the link is on the origin of the target, the client follows it and retries the request once with the token if the target announces.
  • The answer is remembered per target (scheme, host, port, path and query) for one hour, so a target that stops announcing stops getting the token. An answer that is an error other than 404, or that cannot be used, counts as "does not announce" for one minute. A network error is not remembered; the calls waiting for that fetch go out without the token.
  • The record is shared by every client of the process. Clients that reach the same URL through different network paths, such as different proxies, must each get their own: registry=ExtensionRegistry().

ExtensionRegistry(ttl=3600, error_ttl=60, max_targets=1024) changes how long an answer is kept and how many targets are remembered; the values shown are the defaults, in seconds.

Announcing the extension does not make a target trustworthy: anyone can announce it, and every target that does receives the token. Call only targets that the operator of your server configured, never a URL that comes from the caller of a tool or from a model. For A2A, resolve agent cards only from agents the operator configured: the card is trusted as given.

Agent frameworks

Agent frameworks send the token on through the same HTTP clients. Two rules apply to all of them:

  • Open the MCP client, toolset or server inside the request, never at startup, and do not share it between requests. The gateway lists tools for a token, filtered for its user: a session kept across requests would list the tools of one user for another.
  • Use client.httpx with a framework on MCP SDK 1.x and client.httpx2 with one on 2.x. With the wrong one, the framework rejects the client.
Framework MCP SDK Hook
LangChain MCP adapters 0.3, LangGraph1.xhttpx_client_factory; on the LangGraph server, also token_from_run_config
CrewAI 1.15, native mcps=1.xinstall_globally(gateways=[...])
Google ADK 2.14, McpToolset1.x, 2.xhttpx_client_factory and header_provider
OpenAI Agents SDK 0.24, MCPServerStreamableHttp1.x, 2.xhttpx_client_factory
Pydantic AI 2.68, MCPToolset2.xhttp_client
LlamaIndex MCP tools 0.7, BasicMCPClient2.xhttp_client
Microsoft Agent Framework, MCPStreamableHTTPTool1.x up to agent-framework-core 1.22, 2.x from 1.23http_client

LangChain and LangGraph

The adapters open a session per tool call:

from langchain_mcp_adapters.client import MultiServerMCPClient
from indykite_delegated_token.client.httpx import http_client
from indykite_delegated_token.integrations.langchain import token_from_run_config
#
client = MultiServerMCPClient(
    {"target": {"url": TARGET_MCP_URL, "transport": "streamable_http", "httpx_client_factory": http_client}},
    tool_interceptors=[token_from_run_config],  # LangGraph server only
)
tools = await client.get_tools()  # inside the request

On the LangGraph server a run executes in a queue worker, outside the HTTP request. List X-IK-Token in the setting of the deployment for headers copied into the run configuration. The token is then needed twice: to list the tools, which happens before any tool call, and for each tool call. Build the graph for each run and wrap the listing in use_token(run_config_token(config)); token_from_run_config covers the tool calls.

from langchain_core.runnables import RunnableConfig
from indykite_delegated_token import use_token
from indykite_delegated_token.integrations.langchain import run_config_token
#
async def make_graph(config: RunnableConfig):  # the graph factory named in langgraph.json
    with use_token(run_config_token(config)):
        tools = await client.get_tools()
    return create_agent(model, tools)

The token is stored with the run and may appear in traces: leave it out of tracing.

CrewAI

CrewAI takes no HTTP client, so the package hooks httpx for the whole process:

from indykite_delegated_token.client.httpx import install_globally
#
install_globally(gateways=["https://gateway.example.com"])
  • gateways is a list of origins (scheme, host, port). Only requests to those origins are handled, so the token never reaches the LLM provider; they still get the token only if their target announces the extension. A single string raises TypeError, an entry that is not an http or https URL with a host raises ValueError.
  • uninstall_globally() undoes it.
  • Leave cache_tools_list off: CrewAI caches the tool list per URL for the whole process, so one user would get the tools of another.
  • Not supported: MCPServerAdapter of crewai-tools, and tools written as plain functions, which CrewAI runs outside the context of the request.

Google ADK

Pass both the header provider and the client factory of the package. The factory is required: without it the header goes to every server of the toolset, also to those that do not announce the extension.

from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams
from indykite_delegated_token.client.httpx2 import http_client  # client.httpx on MCP SDK 1.x
from indykite_delegated_token.integrations.adk import header_provider
#
toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url=TARGET_MCP_URL, httpx_client_factory=http_client),
    header_provider=header_provider,
)

OpenAI Agents SDK

from agents.mcp import MCPServerStreamableHttp
from indykite_delegated_token.client.httpx2 import http_client  # client.httpx on MCP SDK 1.x
#
async with MCPServerStreamableHttp(params={"url": TARGET_MCP_URL, "httpx_client_factory": http_client}) as server:
    agent = Agent(name="agent", mcp_servers=[server])
    ...

Pydantic AI

from pydantic_ai.mcp import MCPToolset
from indykite_delegated_token.client.httpx2 import http_client
#
async with http_client() as http:
    agent = Agent(model, toolsets=[MCPToolset(TARGET_MCP_URL, http_client=http)])
    ...

LlamaIndex

from llama_index.tools.mcp import BasicMCPClient
from indykite_delegated_token.client.httpx2 import http_client
#
async with http_client() as http:
    client = BasicMCPClient(TARGET_MCP_URL, http_client=http)
    ...

Microsoft Agent Framework

from agent_framework import MCPStreamableHTTPTool
from indykite_delegated_token.client.httpx2 import http_client  # client.httpx up to agent-framework-core 1.22
#
async with http_client() as http, MCPStreamableHTTPTool("target", url=TARGET_MCP_URL, http_client=http) as tool:
    agent = Agent(chat_client, tools=[tool])
    ...

What are the security rules?

  • Reach the server or agent only through its gateway. It trusts any X-IK-Token it receives. The gateway overwrites the header, but a caller that reaches the server directly can send any token.
  • Reach other agents and MCP servers only through gateways, with TLS on every hop. Use network policy to stop calls to anything else.
  • Add the ASGI middleware outermost. Middleware above it still sees the header.
  • Keep the token out of logs and traces. Use strip_header=True in an A2A agent. If you enable OpenTelemetry header capture (OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_*), leave X-IK-Token out of it.

What is not supported?

Case What happens
MCP over the legacy SSE transportThe clients use Streamable HTTP only.
A2A over gRPC through the gatewayThe gateway exposes JSON-RPC only. The middleware works for JSON-RPC and REST.
A2A push notifications with the tokenDo not pass the HTTP clients of the package to the push notification sender of a2a-sdk: every push would carry the token of the request that started the task.
FastMCP tools with task=TrueThey see no token.
CrewAI MCPServerAdapter and plain-function toolsThey run outside the context of the request and send no token.

How do I check a chain end to end?

The repository of the package has two runnable samples, each with a Dockerfile: examples/sample_mcp_server, an MCP server with the tools call_mcp_tool and ask_agent, and examples/sample_a2a_agent, an A2A agent that does the same without a model. Both call an MCP server and an A2A agent through their gateways.

docker build -f examples/sample_a2a_agent/Dockerfile -t indykite-delegated-token-sample-agent .
docker run -p 8000:8000 \
  -e PUBLIC_URL=https://sample-agent.internal.example.com \
  -e TARGET_MCP_URL=https://gateway.example.com/mcp \
  -e TARGET_AGENT_URL=https://agent-gateway.example.com \
  indykite-delegated-token-sample-agent
Variable Meaning
TARGET_MCP_URLRequired. The MCP endpoint to call, at its gateway.
TARGET_AGENT_URLRequired. The base URL of the A2A agent to call, at its gateway.
PUBLIC_URLSample agent only: the URL of the agent in its card. http://localhost:<PORT> when left out.
ALLOW_HTTP1 to also send the token over plain HTTP, such as to a gateway in a private network.
ALLOWED_HOSTSSample MCP server only: comma-separated Host headers the server accepts, such as sample-mcp:*. Every Host is accepted when left out.
HOST, PORTWhere the sample listens, 0.0.0.0:8000 by default.
  1. Deploy the sample agent behind a gateway with a Token Service, and point TARGET_MCP_URL and TARGET_AGENT_URL at targets that are behind gateways with a Token Service too.
  2. Send a message to the gateway of the sample agent with a user token: hi for the A2A target, or a data part {"mcp_tool": "whoami"} for an MCP target that has such a tool.
  3. In the logs of the target, check that it received X-IK-Token, and that the chain of the token has the user, the gateway of the sample agent and the gateway of the target.

When the target gets no token, check in this order: its gateway has token_service and so announces the extension; the URL is https, or allow_http is set; the client was opened inside the request; the client module matches the MCP SDK in use.

Related