|
| 1 | +"""Interceptor interfaces and types for MCP client tool call lifecycle management. |
| 2 | +
|
| 3 | +This module provides an interceptor interface for wrapping and controlling |
| 4 | +MCP tool call execution with a handler callback pattern. |
| 5 | +
|
| 6 | +In the future, we might add more interceptors for other parts of the |
| 7 | +request / result lifecycle, for example to support elicitation. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +from dataclasses import dataclass, replace |
| 13 | +from typing import TYPE_CHECKING, Any, Protocol |
| 14 | + |
| 15 | +from mcp.types import CallToolResult |
| 16 | +from typing_extensions import NotRequired, TypedDict, Unpack |
| 17 | + |
| 18 | +if TYPE_CHECKING: |
| 19 | + from collections.abc import Awaitable, Callable |
| 20 | + |
| 21 | + |
| 22 | +MCPToolCallResult = CallToolResult |
| 23 | + |
| 24 | + |
| 25 | +class _MCPToolCallRequestOverrides(TypedDict, total=False): |
| 26 | + """Possible overrides for MCPToolCallRequest.override() method. |
| 27 | +
|
| 28 | + Only includes modifiable request fields, not context fields like |
| 29 | + server_name and runtime which are read-only. |
| 30 | + """ |
| 31 | + |
| 32 | + name: NotRequired[str] |
| 33 | + args: NotRequired[dict[str, Any]] |
| 34 | + headers: NotRequired[dict[str, Any] | None] |
| 35 | + |
| 36 | + |
| 37 | +@dataclass |
| 38 | +class MCPToolCallRequest: |
| 39 | + """Tool execution request passed to MCP tool call interceptors. |
| 40 | +
|
| 41 | + Similar to LangChain's ToolCallRequest but adapted for MCP remote tools. |
| 42 | + MCP tools don't have local BaseTool instances, so this flattens the call |
| 43 | + data and context into a single object. |
| 44 | +
|
| 45 | + Modifiable fields (override these to change behavior): |
| 46 | + name: Tool name to invoke. |
| 47 | + args: Tool arguments as key-value pairs. |
| 48 | + headers: HTTP headers for applicable transports (SSE, HTTP). |
| 49 | +
|
| 50 | + Context fields (read-only, use for routing/logging): |
| 51 | + server_name: Name of the MCP server handling the tool. |
| 52 | + runtime: LangGraph runtime context (optional, None if outside graph). |
| 53 | + """ |
| 54 | + |
| 55 | + name: str |
| 56 | + args: dict[str, Any] |
| 57 | + server_name: str # Context: MCP server name |
| 58 | + headers: dict[str, Any] | None = None # Modifiable: HTTP headers |
| 59 | + runtime: object | None = None # Context: LangGraph runtime (if any) |
| 60 | + |
| 61 | + def override( |
| 62 | + self, **overrides: Unpack[_MCPToolCallRequestOverrides] |
| 63 | + ) -> MCPToolCallRequest: |
| 64 | + """Replace the request with a new request with the given overrides. |
| 65 | +
|
| 66 | + Returns a new `MCPToolCallRequest` instance with the specified |
| 67 | + attributes replaced. This follows an immutable pattern, leaving the |
| 68 | + original request unchanged. |
| 69 | +
|
| 70 | + Args: |
| 71 | + **overrides: Keyword arguments for attributes to override. |
| 72 | + Supported keys: |
| 73 | + - name: Tool name |
| 74 | + - args: Tool arguments |
| 75 | + - headers: HTTP headers |
| 76 | +
|
| 77 | + Returns: |
| 78 | + New MCPToolCallRequest instance with specified overrides |
| 79 | + applied. |
| 80 | +
|
| 81 | + Note: |
| 82 | + Context fields (server_name, runtime) cannot be overridden as |
| 83 | + they are read-only. |
| 84 | +
|
| 85 | + Examples: |
| 86 | + ```python |
| 87 | + # Modify tool arguments |
| 88 | + new_request = request.override(args={"value": 10}) |
| 89 | +
|
| 90 | + # Change tool name |
| 91 | + new_request = request.override(name="different_tool") |
| 92 | + ``` |
| 93 | + """ |
| 94 | + return replace(self, **overrides) |
| 95 | + |
| 96 | + |
| 97 | +class ToolCallInterceptor(Protocol): |
| 98 | + """Protocol for tool call interceptors using handler callback pattern. |
| 99 | +
|
| 100 | + Interceptors wrap tool execution to enable request/response modification, |
| 101 | + retry logic, caching, rate limiting, and other cross-cutting concerns. |
| 102 | + Multiple interceptors compose in "onion" pattern (first is outermost). |
| 103 | +
|
| 104 | + The handler can be called multiple times (retry), skipped (caching/short-circuit), |
| 105 | + or wrapped with error handling. Each handler call is independent. |
| 106 | +
|
| 107 | + Similar to LangChain's middleware pattern but adapted for MCP remote tools. |
| 108 | + """ |
| 109 | + |
| 110 | + async def __call__( |
| 111 | + self, |
| 112 | + request: MCPToolCallRequest, |
| 113 | + handler: Callable[[MCPToolCallRequest], Awaitable[MCPToolCallResult]], |
| 114 | + ) -> MCPToolCallResult: |
| 115 | + """Intercept tool execution with control over handler invocation. |
| 116 | +
|
| 117 | + Args: |
| 118 | + request: Tool call request containing name, args, headers, and context |
| 119 | + (server_name, runtime). Access context fields like request.server_name. |
| 120 | + handler: Async callable executing the tool. Can be called multiple |
| 121 | + times, skipped, or wrapped for error handling. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + Final MCPToolCallResult from tool execution or interceptor logic. |
| 125 | + """ |
| 126 | + ... |
0 commit comments