Coverage for little_loops / mcp_call.py: 0%
129 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
1"""mcp-call — thin CLI wrapper for direct MCP tool invocation.
3Usage:
4 mcp-call server/tool-name '{"param": "value"}'
6Reads .mcp.json from the current working directory, spawns the MCP server
7subprocess, performs the JSON-RPC initialize handshake, calls tools/call,
8and writes the MCP response envelope to stdout.
10Exit codes:
11 0 → success (isError: false)
12 1 → tool_error (isError: true)
13 124 → timeout (transport-level)
14 127 → not_found (server or tool missing from .mcp.json)
15 2 → usage/config error
16"""
18from __future__ import annotations
20import json
21import subprocess
22import sys
23import threading
24import time
25from pathlib import Path
26from typing import Any
29MCP_PROTOCOL_VERSION = "2024-11-05"
30_DEFAULT_TIMEOUT = 30 # seconds
33def _load_mcp_config(cwd: Path) -> dict[str, Any]:
34 """Load .mcp.json from the current working directory.
36 Args:
37 cwd: Directory to search for .mcp.json
39 Returns:
40 Parsed .mcp.json content
42 Raises:
43 FileNotFoundError: If .mcp.json not found
44 json.JSONDecodeError: If .mcp.json is invalid JSON
45 """
46 mcp_path = cwd / ".mcp.json"
47 if not mcp_path.exists():
48 raise FileNotFoundError(f".mcp.json not found in {cwd}")
49 return json.loads(mcp_path.read_text())
52def _find_server_config(mcp_config: dict[str, Any], server_name: str) -> dict[str, Any] | None:
53 """Find server configuration by name in .mcp.json.
55 Args:
56 mcp_config: Parsed .mcp.json content
57 server_name: Server name to find
59 Returns:
60 Server config dict, or None if not found
61 """
62 servers = mcp_config.get("mcpServers", {})
63 return servers.get(server_name)
66def _send_jsonrpc(
67 proc: subprocess.Popen[str],
68 request: dict[str, Any],
69 request_id: int | None,
70 timeout: float,
71) -> dict[str, Any] | None:
72 """Send a JSON-RPC request and optionally wait for a response.
74 Args:
75 proc: Running MCP server process
76 request: JSON-RPC request dict
77 request_id: Expected response id (None for notifications)
78 timeout: Seconds to wait for response
80 Returns:
81 Parsed response dict, or None for notifications
82 """
83 assert proc.stdin is not None
84 line = json.dumps(request) + "\n"
85 proc.stdin.write(line)
86 proc.stdin.flush()
88 if request_id is None:
89 # Notification — no response expected
90 return None
92 # Read response lines until we find the matching id or timeout
93 assert proc.stdout is not None
94 deadline = time.monotonic() + timeout
95 while time.monotonic() < deadline:
96 proc.stdout.readable()
97 try:
98 response_line = proc.stdout.readline()
99 except (OSError, ValueError):
100 break
101 if not response_line:
102 break
103 response_line = response_line.strip()
104 if not response_line:
105 continue
106 try:
107 response = json.loads(response_line)
108 if response.get("id") == request_id:
109 return response
110 except json.JSONDecodeError:
111 continue
113 return None
116def call_mcp_tool(
117 server_name: str,
118 tool_name: str,
119 params: dict[str, Any],
120 timeout: int = _DEFAULT_TIMEOUT,
121 cwd: Path | None = None,
122) -> tuple[dict[str, Any], int]:
123 """Call an MCP tool via JSON-RPC and return the response envelope + exit code.
125 Args:
126 server_name: MCP server name (from .mcp.json mcpServers key)
127 tool_name: Tool name to call
128 params: Tool arguments
129 timeout: Timeout in seconds
130 cwd: Directory containing .mcp.json (defaults to Path.cwd())
132 Returns:
133 Tuple of (MCP response envelope dict, exit code)
134 Exit codes:
135 0 → success
136 1 → tool_error
137 124 → timeout
138 127 → not_found
139 2 → config/usage error
140 """
141 if cwd is None:
142 cwd = Path.cwd()
144 # Load .mcp.json
145 try:
146 mcp_config = _load_mcp_config(cwd)
147 except FileNotFoundError as e:
148 return {"isError": True, "content": [{"type": "text", "text": str(e)}]}, 127
149 except json.JSONDecodeError as e:
150 return {"isError": True, "content": [{"type": "text", "text": f"Invalid .mcp.json: {e}"}]}, 2
152 # Find server config
153 server_config = _find_server_config(mcp_config, server_name)
154 if server_config is None:
155 return {
156 "isError": True,
157 "content": [{"type": "text", "text": f"Server '{server_name}' not found in .mcp.json"}],
158 }, 127
160 # Build server command
161 command = server_config.get("command")
162 if not command:
163 return {
164 "isError": True,
165 "content": [{"type": "text", "text": f"Server '{server_name}' has no 'command' in .mcp.json"}],
166 }, 2
168 args = server_config.get("args", [])
169 env_overrides = server_config.get("env", {})
171 import os
173 env = os.environ.copy()
174 env.update({k: str(v) for k, v in env_overrides.items()})
176 cmd = [command] + args
178 # Spawn server
179 try:
180 proc = subprocess.Popen(
181 cmd,
182 stdin=subprocess.PIPE,
183 stdout=subprocess.PIPE,
184 stderr=subprocess.PIPE,
185 text=True,
186 env=env,
187 )
188 except FileNotFoundError:
189 return {
190 "isError": True,
191 "content": [{"type": "text", "text": f"Server command not found: {command}"}],
192 }, 127
194 stderr_chunks: list[str] = []
196 def _drain_stderr() -> None:
197 assert proc.stderr is not None
198 for line in proc.stderr:
199 stderr_chunks.append(line)
201 stderr_thread = threading.Thread(target=_drain_stderr, daemon=True)
202 stderr_thread.start()
204 try:
205 # Step 1: Send initialize request
206 init_response = _send_jsonrpc(
207 proc,
208 {
209 "jsonrpc": "2.0",
210 "id": 1,
211 "method": "initialize",
212 "params": {
213 "protocolVersion": MCP_PROTOCOL_VERSION,
214 "capabilities": {},
215 "clientInfo": {"name": "mcp-call", "version": "1.0"},
216 },
217 },
218 request_id=1,
219 timeout=timeout,
220 )
222 if init_response is None:
223 proc.kill()
224 return {
225 "isError": True,
226 "content": [{"type": "text", "text": "No response to initialize request (timeout)"}],
227 }, 124
229 if "error" in init_response:
230 proc.kill()
231 return {
232 "isError": True,
233 "content": [{"type": "text", "text": f"Initialize failed: {init_response['error']}"}],
234 }, 1
236 # Step 2: Send initialized notification
237 _send_jsonrpc(
238 proc,
239 {"jsonrpc": "2.0", "method": "notifications/initialized"},
240 request_id=None,
241 timeout=0,
242 )
244 # Step 3: Call tools/call
245 call_response = _send_jsonrpc(
246 proc,
247 {
248 "jsonrpc": "2.0",
249 "id": 2,
250 "method": "tools/call",
251 "params": {"name": tool_name, "arguments": params},
252 },
253 request_id=2,
254 timeout=timeout,
255 )
257 if call_response is None:
258 proc.kill()
259 return {
260 "isError": True,
261 "content": [{"type": "text", "text": "No response to tools/call request (timeout)"}],
262 }, 124
264 if "error" in call_response:
265 err = call_response["error"]
266 # JSON-RPC method not found → tool not found
267 if isinstance(err, dict) and err.get("code") == -32601:
268 return {
269 "isError": True,
270 "content": [{"type": "text", "text": f"Tool '{tool_name}' not found on server '{server_name}'"}],
271 }, 127
272 return {
273 "isError": True,
274 "content": [{"type": "text", "text": f"tools/call error: {err}"}],
275 }, 1
277 # Unwrap result from JSON-RPC envelope
278 result = call_response.get("result", {})
279 is_error = result.get("isError", False)
280 exit_code = 1 if is_error else 0
281 return result, exit_code
283 except subprocess.TimeoutExpired:
284 proc.kill()
285 return {
286 "isError": True,
287 "content": [{"type": "text", "text": "MCP tool call timed out"}],
288 }, 124
289 finally:
290 try:
291 proc.terminate()
292 proc.wait(timeout=5)
293 except Exception:
294 proc.kill()
295 stderr_thread.join(timeout=5)
298def main() -> None:
299 """Entry point for mcp-call CLI."""
300 if len(sys.argv) < 3:
301 print(
302 "Usage: mcp-call server/tool-name '{\"param\": \"value\"}'",
303 file=sys.stderr,
304 )
305 sys.exit(2)
307 spec = sys.argv[1]
308 params_json = sys.argv[2]
310 # Parse server/tool-name
311 if "/" not in spec:
312 print(
313 f"Error: spec must be 'server/tool-name', got: {spec!r}",
314 file=sys.stderr,
315 )
316 sys.exit(2)
318 server_name, tool_name = spec.split("/", 1)
320 # Parse params JSON
321 try:
322 params = json.loads(params_json)
323 except json.JSONDecodeError as e:
324 print(f"Error: invalid params JSON: {e}", file=sys.stderr)
325 sys.exit(2)
327 if not isinstance(params, dict):
328 print("Error: params must be a JSON object", file=sys.stderr)
329 sys.exit(2)
331 envelope, exit_code = call_mcp_tool(
332 server_name=server_name,
333 tool_name=tool_name,
334 params=params,
335 )
337 print(json.dumps(envelope))
338 sys.exit(exit_code)
341if __name__ == "__main__":
342 main()