-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy path__init__.py
More file actions
406 lines (367 loc) · 13.7 KB
/
__init__.py
File metadata and controls
406 lines (367 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
"""Claude SDK for Python."""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Generic, TypeVar
from mcp.types import ToolAnnotations
from ._errors import (
ClaudeSDKError,
CLIConnectionError,
CLIJSONDecodeError,
CLINotFoundError,
ProcessError,
)
from ._internal.sessions import get_session_messages, list_sessions
from ._internal.transport import Transport
from ._version import __version__
from .client import ClaudeSDKClient
from .query import query
from .types import (
AgentDefinition,
AssistantMessage,
BaseHookInput,
CanUseTool,
ClaudeAgentOptions,
ContentBlock,
HookCallback,
HookContext,
HookInput,
HookJSONOutput,
HookMatcher,
McpSdkServerConfig,
McpServerConfig,
Message,
NotificationHookInput,
NotificationHookSpecificOutput,
PermissionMode,
PermissionRequestHookInput,
PermissionRequestHookSpecificOutput,
PermissionResult,
PermissionResultAllow,
PermissionResultDeny,
PermissionUpdate,
PostToolUseFailureHookInput,
PostToolUseFailureHookSpecificOutput,
PostToolUseHookInput,
PreCompactHookInput,
PreToolUseHookInput,
ResultMessage,
SandboxIgnoreViolations,
SandboxNetworkConfig,
SandboxSettings,
SdkBeta,
SdkPluginConfig,
SDKSessionInfo,
SessionMessage,
SettingSource,
StopHookInput,
SubagentStartHookInput,
SubagentStartHookSpecificOutput,
SubagentStopHookInput,
SystemMessage,
TextBlock,
ThinkingBlock,
ThinkingConfig,
ThinkingConfigAdaptive,
ThinkingConfigDisabled,
ThinkingConfigEnabled,
ToolPermissionContext,
ToolResultBlock,
ToolUseBlock,
UserMessage,
UserPromptSubmitHookInput,
)
# MCP Server Support
T = TypeVar("T")
@dataclass
class SdkMcpTool(Generic[T]):
"""Definition for an SDK MCP tool."""
name: str
description: str
input_schema: type[T] | dict[str, Any]
handler: Callable[[T], Awaitable[dict[str, Any]]]
annotations: ToolAnnotations | None = None
def tool(
name: str,
description: str,
input_schema: type | dict[str, Any],
annotations: ToolAnnotations | None = None,
) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]:
"""Decorator for defining MCP tools with type safety.
Creates a tool that can be used with SDK MCP servers. The tool runs
in-process within your Python application, providing better performance
than external MCP servers.
Args:
name: Unique identifier for the tool. This is what Claude will use
to reference the tool in function calls.
description: Human-readable description of what the tool does.
This helps Claude understand when to use the tool.
input_schema: Schema defining the tool's input parameters.
Can be either:
- A dictionary mapping parameter names to types (e.g., {"text": str})
- A TypedDict class for more complex schemas
- A JSON Schema dictionary for full validation
Returns:
A decorator function that wraps the tool implementation and returns
an SdkMcpTool instance ready for use with create_sdk_mcp_server().
Example:
Basic tool with simple schema:
>>> @tool("greet", "Greet a user", {"name": str})
... async def greet(args):
... return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}
Tool with multiple parameters:
>>> @tool("add", "Add two numbers", {"a": float, "b": float})
... async def add_numbers(args):
... result = args["a"] + args["b"]
... return {"content": [{"type": "text", "text": f"Result: {result}"}]}
Tool with error handling:
>>> @tool("divide", "Divide two numbers", {"a": float, "b": float})
... async def divide(args):
... if args["b"] == 0:
... return {"content": [{"type": "text", "text": "Error: Division by zero"}], "is_error": True}
... return {"content": [{"type": "text", "text": f"Result: {args['a'] / args['b']}"}]}
Notes:
- The tool function must be async (defined with async def)
- The function receives a single dict argument with the input parameters
- The function should return a dict with a "content" key containing the response
- Errors can be indicated by including "is_error": True in the response
"""
def decorator(
handler: Callable[[Any], Awaitable[dict[str, Any]]],
) -> SdkMcpTool[Any]:
return SdkMcpTool(
name=name,
description=description,
input_schema=input_schema,
handler=handler,
annotations=annotations,
)
return decorator
def create_sdk_mcp_server(
name: str, version: str = "1.0.0", tools: list[SdkMcpTool[Any]] | None = None
) -> McpSdkServerConfig:
"""Create an in-process MCP server that runs within your Python application.
Unlike external MCP servers that run as separate processes, SDK MCP servers
run directly in your application's process. This provides:
- Better performance (no IPC overhead)
- Simpler deployment (single process)
- Easier debugging (same process)
- Direct access to your application's state
Args:
name: Unique identifier for the server. This name is used to reference
the server in the mcp_servers configuration.
version: Server version string. Defaults to "1.0.0". This is for
informational purposes and doesn't affect functionality.
tools: List of SdkMcpTool instances created with the @tool decorator.
These are the functions that Claude can call through this server.
If None or empty, the server will have no tools (rarely useful).
Returns:
McpSdkServerConfig: A configuration object that can be passed to
ClaudeAgentOptions.mcp_servers. This config contains the server
instance and metadata needed for the SDK to route tool calls.
Example:
Simple calculator server:
>>> @tool("add", "Add numbers", {"a": float, "b": float})
... async def add(args):
... return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}
>>>
>>> @tool("multiply", "Multiply numbers", {"a": float, "b": float})
... async def multiply(args):
... return {"content": [{"type": "text", "text": f"Product: {args['a'] * args['b']}"}]}
>>>
>>> calculator = create_sdk_mcp_server(
... name="calculator",
... version="2.0.0",
... tools=[add, multiply]
... )
>>>
>>> # Use with Claude
>>> options = ClaudeAgentOptions(
... mcp_servers={"calc": calculator},
... allowed_tools=["add", "multiply"]
... )
Server with application state access:
>>> class DataStore:
... def __init__(self):
... self.items = []
...
>>> store = DataStore()
>>>
>>> @tool("add_item", "Add item to store", {"item": str})
... async def add_item(args):
... store.items.append(args["item"])
... return {"content": [{"type": "text", "text": f"Added: {args['item']}"}]}
>>>
>>> server = create_sdk_mcp_server("store", tools=[add_item])
Notes:
- The server runs in the same process as your Python application
- Tools have direct access to your application's variables and state
- No subprocess or IPC overhead for tool calls
- Server lifecycle is managed automatically by the SDK
See Also:
- tool(): Decorator for creating tool functions
- ClaudeAgentOptions: Configuration for using servers with query()
"""
from mcp.server import Server
from mcp.types import ImageContent, TextContent, Tool
# Create MCP server instance
server = Server(name, version=version)
# Register tools if provided
if tools:
# Store tools for access in handlers
tool_map = {tool_def.name: tool_def for tool_def in tools}
# Register list_tools handler to expose available tools
@server.list_tools() # type: ignore[no-untyped-call,untyped-decorator]
async def list_tools() -> list[Tool]:
"""Return the list of available tools."""
tool_list = []
for tool_def in tools:
# Convert input_schema to JSON Schema format
if isinstance(tool_def.input_schema, dict):
# Check if it's already a JSON schema
if (
"type" in tool_def.input_schema
and "properties" in tool_def.input_schema
):
schema = tool_def.input_schema
else:
# Simple dict mapping names to types - convert to JSON schema
properties = {}
for param_name, param_type in tool_def.input_schema.items():
if param_type is str:
properties[param_name] = {"type": "string"}
elif param_type is int:
properties[param_name] = {"type": "integer"}
elif param_type is float:
properties[param_name] = {"type": "number"}
elif param_type is bool:
properties[param_name] = {"type": "boolean"}
else:
properties[param_name] = {"type": "string"} # Default
schema = {
"type": "object",
"properties": properties,
"required": list(properties.keys()),
}
else:
# For TypedDict or other types, create basic schema
schema = {"type": "object", "properties": {}}
tool_list.append(
Tool(
name=tool_def.name,
description=tool_def.description,
inputSchema=schema,
annotations=tool_def.annotations,
)
)
return tool_list
# Register call_tool handler to execute tools
@server.call_tool() # type: ignore[untyped-decorator]
async def call_tool(name: str, arguments: dict[str, Any]) -> Any:
"""Execute a tool by name with given arguments."""
if name not in tool_map:
raise ValueError(f"Tool '{name}' not found")
tool_def = tool_map[name]
# Call the tool's handler with arguments
result = await tool_def.handler(arguments)
# Convert result to MCP format
# The decorator expects us to return the content, not a CallToolResult
# It will wrap our return value in CallToolResult
content: list[TextContent | ImageContent] = []
if "content" in result:
for item in result["content"]:
if item.get("type") == "text":
content.append(TextContent(type="text", text=item["text"]))
if item.get("type") == "image":
content.append(
ImageContent(
type="image",
data=item["data"],
mimeType=item["mimeType"],
)
)
# Return just the content list - the decorator wraps it
return content
# Return SDK server configuration
return McpSdkServerConfig(type="sdk", name=name, instance=server)
__all__ = [
# Main exports
"query",
"__version__",
# Transport
"Transport",
"ClaudeSDKClient",
# Types
"PermissionMode",
"McpServerConfig",
"McpSdkServerConfig",
"UserMessage",
"AssistantMessage",
"SystemMessage",
"ResultMessage",
"Message",
"ClaudeAgentOptions",
"TextBlock",
"ThinkingBlock",
"ThinkingConfig",
"ThinkingConfigAdaptive",
"ThinkingConfigEnabled",
"ThinkingConfigDisabled",
"ToolUseBlock",
"ToolResultBlock",
"ContentBlock",
# Tool callbacks
"CanUseTool",
"ToolPermissionContext",
"PermissionResult",
"PermissionResultAllow",
"PermissionResultDeny",
"PermissionUpdate",
# Hook support
"HookCallback",
"HookContext",
"HookInput",
"BaseHookInput",
"PreToolUseHookInput",
"PostToolUseHookInput",
"PostToolUseFailureHookInput",
"PostToolUseFailureHookSpecificOutput",
"UserPromptSubmitHookInput",
"StopHookInput",
"SubagentStopHookInput",
"PreCompactHookInput",
"NotificationHookInput",
"SubagentStartHookInput",
"PermissionRequestHookInput",
"NotificationHookSpecificOutput",
"SubagentStartHookSpecificOutput",
"PermissionRequestHookSpecificOutput",
"HookJSONOutput",
"HookMatcher",
# Agent support
"AgentDefinition",
"SettingSource",
# Plugin support
"SdkPluginConfig",
# Session listing
"list_sessions",
"get_session_messages",
"SDKSessionInfo",
"SessionMessage",
# Beta support
"SdkBeta",
# Sandbox support
"SandboxSettings",
"SandboxNetworkConfig",
"SandboxIgnoreViolations",
# MCP Server Support
"create_sdk_mcp_server",
"tool",
"SdkMcpTool",
"ToolAnnotations",
# Errors
"ClaudeSDKError",
"CLIConnectionError",
"CLINotFoundError",
"ProcessError",
"CLIJSONDecodeError",
]