Skip to content

Commit 17f7eee

Browse files
committed
InjectedState in MCP tools
usage: On the MCP server side, specify the key to map to the state with annotations: @mcp.tool(annotations={"injected_state": "state"}) def tool(a, b, state): pass On the client side, it is handled automatically
1 parent 7eb4098 commit 17f7eee

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

langchain_mcp_adapters/tools.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
tools, handle tool execution, and manage tool conversion between the two formats.
55
"""
66

7-
from typing import Any, cast, get_args
7+
from typing import Any, cast, get_args, Annotated
88

99
from langchain_core.tools import (
1010
BaseTool,
@@ -20,6 +20,7 @@
2020
from mcp.types import Tool as MCPTool
2121
from pydantic import BaseModel, create_model
2222

23+
2324
from langchain_mcp_adapters.sessions import Connection, create_session
2425

2526
NonTextContent = ImageContent | EmbeddedResource
@@ -135,11 +136,34 @@ async def call_tool(
135136
else:
136137
call_tool_result = await session.call_tool(tool.name, arguments)
137138
return _convert_call_tool_result(call_tool_result)
139+
140+
type_map = {
141+
'integer': int,
142+
'float': float,
143+
'string': str,
144+
'bool': bool,
145+
'object': dict,
146+
'bytes': bytes
147+
}
148+
149+
args = tool.inputSchema
150+
151+
model_fields = {}
152+
injected_state = tool.annotations.model_extra.get('injected_state')
153+
if injected_state:
154+
from langgraph.prebuilt import InjectedState
155+
for field, props in args['properties'].items():
156+
field_type = type_map.get(props['type'], dict)
157+
if field == injected_state:
158+
field_type = Annotated[dict, InjectedState]
159+
model_fields[field] = field_type
160+
161+
args_schema = create_model(tool.name, **{k: (v, ...) for k, v in model_fields.items()})
138162

139163
return StructuredTool(
140164
name=tool.name,
141165
description=tool.description or "",
142-
args_schema=tool.inputSchema,
166+
args_schema=args_schema,
143167
coroutine=call_tool,
144168
response_format="content_and_artifact",
145169
metadata=tool.annotations.model_dump() if tool.annotations else None,

0 commit comments

Comments
 (0)