dataprep-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. dataprep_mcp/__init__.py +0 -0
  2. dataprep_mcp/__main__.py +76 -0
  3. dataprep_mcp/auth_cli.py +96 -0
  4. dataprep_mcp/cli.py +0 -0
  5. dataprep_mcp/client/__init__.py +0 -0
  6. dataprep_mcp/client/agent.py +144 -0
  7. dataprep_mcp/client/cli.py +210 -0
  8. dataprep_mcp/client/config.py +48 -0
  9. dataprep_mcp/client/forms.py +94 -0
  10. dataprep_mcp/client/hub.py +158 -0
  11. dataprep_mcp/engine/__init__.py +0 -0
  12. dataprep_mcp/engine/distributions.py +64 -0
  13. dataprep_mcp/engine/loading.py +70 -0
  14. dataprep_mcp/engine/ml_recommend.py +301 -0
  15. dataprep_mcp/engine/outliers.py +96 -0
  16. dataprep_mcp/engine/preprocessing.py +240 -0
  17. dataprep_mcp/engine/profiling.py +204 -0
  18. dataprep_mcp/engine/quality.py +198 -0
  19. dataprep_mcp/engine/relationships.py +114 -0
  20. dataprep_mcp/engine/target.py +93 -0
  21. dataprep_mcp/engine/versioning.py +0 -0
  22. dataprep_mcp/schemas/__init__.py +0 -0
  23. dataprep_mcp/schemas/dashboard.py +84 -0
  24. dataprep_mcp/schemas/dataset.py +34 -0
  25. dataprep_mcp/schemas/ml.py +66 -0
  26. dataprep_mcp/schemas/preprocessing.py +84 -0
  27. dataprep_mcp/schemas/profile.py +117 -0
  28. dataprep_mcp/server/__init__.py +0 -0
  29. dataprep_mcp/server/app.py +45 -0
  30. dataprep_mcp/server/approval.py +103 -0
  31. dataprep_mcp/server/auth.py +70 -0
  32. dataprep_mcp/server/completions.py +57 -0
  33. dataprep_mcp/server/dashboard.py +147 -0
  34. dataprep_mcp/server/ml_tools.py +50 -0
  35. dataprep_mcp/server/preprocessing_tools.py +213 -0
  36. dataprep_mcp/server/progress.py +111 -0
  37. dataprep_mcp/server/prompts.py +101 -0
  38. dataprep_mcp/server/resources.py +103 -0
  39. dataprep_mcp/server/security.py +53 -0
  40. dataprep_mcp/server/session.py +115 -0
  41. dataprep_mcp/server/tools.py +175 -0
  42. dataprep_mcp/server/views.py +202 -0
  43. dataprep_mcp/ui/dashboard.html +549 -0
  44. dataprep_mcp-0.1.0.dist-info/METADATA +158 -0
  45. dataprep_mcp-0.1.0.dist-info/RECORD +49 -0
  46. dataprep_mcp-0.1.0.dist-info/WHEEL +5 -0
  47. dataprep_mcp-0.1.0.dist-info/entry_points.txt +4 -0
  48. dataprep_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
  49. dataprep_mcp-0.1.0.dist-info/top_level.txt +1 -0
File without changes
@@ -0,0 +1,76 @@
1
+ """Start the DataPrep MCP server.
2
+
3
+ dataprep-mcp # stdio (Claude Desktop, MCP Inspector)
4
+ dataprep-mcp --transport http --port 8000 # remote: Streamable HTTP at /mcp
5
+ """
6
+
7
+ import argparse
8
+ import ipaddress
9
+ import logging
10
+ import sys
11
+
12
+ from dataprep_mcp.server.app import mcp
13
+ from dataprep_mcp.server.auth import AuthConfigError, verifier_from_env
14
+
15
+ log = logging.getLogger("dataprep_mcp")
16
+
17
+
18
+ def is_loopback(host: str) -> bool:
19
+ if host == "localhost":
20
+ return True
21
+ try:
22
+ return ipaddress.ip_address(host).is_loopback
23
+ except ValueError:
24
+ return False
25
+
26
+
27
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
28
+ parser = argparse.ArgumentParser(prog="dataprep-mcp", description="DataPrep MCP server")
29
+ parser.add_argument("--transport", choices=["stdio", "http"], default="stdio")
30
+ parser.add_argument("--host", default="127.0.0.1", help="HTTP only (default 127.0.0.1)")
31
+ parser.add_argument("--port", type=int, default=8000, help="HTTP only (default 8000)")
32
+ parser.add_argument("--path", default="/mcp", help="HTTP endpoint path (default /mcp)")
33
+ parser.add_argument(
34
+ "--allow-no-auth",
35
+ action="store_true",
36
+ help="HTTP without tokens; only allowed on a loopback host such as 127.0.0.1",
37
+ )
38
+ return parser.parse_args(argv)
39
+
40
+
41
+ def main(argv: list[str] | None = None) -> None:
42
+ logging.basicConfig(
43
+ level=logging.INFO,
44
+ stream=sys.stderr, # stdout carries the protocol in stdio mode
45
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
46
+ )
47
+ args = parse_args(argv)
48
+
49
+ if args.transport == "stdio":
50
+ mcp.run()
51
+ return
52
+
53
+ try:
54
+ verifier = verifier_from_env()
55
+ except AuthConfigError as exc:
56
+ sys.exit(f"Auth configuration error: {exc}")
57
+
58
+ if verifier is not None:
59
+ mcp.auth = verifier
60
+ log.info("Token authentication on")
61
+ elif args.allow_no_auth and is_loopback(args.host):
62
+ log.warning("No authentication: only programs on this computer can connect")
63
+ elif args.allow_no_auth:
64
+ sys.exit("--allow-no-auth only works with a loopback --host such as 127.0.0.1.")
65
+ else:
66
+ sys.exit(
67
+ "HTTP needs authentication. Set DATAPREP_AUTH_PUBLIC_KEY_FILE (see "
68
+ "`dataprep-mcp-auth keys`) or DATAPREP_AUTH_JWKS_URI, or add --allow-no-auth "
69
+ "for local testing."
70
+ )
71
+
72
+ mcp.run(transport="http", host=args.host, port=args.port, path=args.path)
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()
@@ -0,0 +1,96 @@
1
+ """Development helper: create a signing key pair and issue tokens for testing.
2
+
3
+ dataprep-mcp-auth keys --out keys
4
+ dataprep-mcp-auth token --key keys/private.pem --subject alice
5
+
6
+ In production an identity provider issues tokens; the server only needs the
7
+ public key (or the provider's JWKS URL). Never commit the private key.
8
+ """
9
+
10
+ import argparse
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ from cryptography.hazmat.primitives import serialization
15
+ from cryptography.hazmat.primitives.asymmetric import rsa
16
+ from fastmcp.server.auth.providers.jwt import RSAKeyPair
17
+ from pydantic import SecretStr
18
+
19
+ from dataprep_mcp.server.auth import DEFAULT_AUDIENCE, DEFAULT_ISSUER
20
+
21
+
22
+ def write_keys(out: Path) -> tuple[Path, Path]:
23
+ out.mkdir(parents=True, exist_ok=True)
24
+ private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
25
+ private_pem = private.private_bytes(
26
+ serialization.Encoding.PEM,
27
+ serialization.PrivateFormat.PKCS8,
28
+ serialization.NoEncryption(),
29
+ )
30
+ public_pem = private.public_key().public_bytes(
31
+ serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
32
+ )
33
+ private_path, public_path = out / "private.pem", out / "public.pem"
34
+ private_path.write_bytes(private_pem)
35
+ public_path.write_bytes(public_pem)
36
+ return private_path, public_path
37
+
38
+
39
+ def make_token(
40
+ key_file: Path,
41
+ subject: str,
42
+ *,
43
+ issuer: str = DEFAULT_ISSUER,
44
+ audience: str = DEFAULT_AUDIENCE,
45
+ scopes: list[str] | None = None,
46
+ hours: float = 8,
47
+ ) -> str:
48
+ private_pem = key_file.read_bytes()
49
+ private = serialization.load_pem_private_key(private_pem, password=None)
50
+ public_pem = private.public_key().public_bytes(
51
+ serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
52
+ )
53
+ pair = RSAKeyPair(private_key=SecretStr(private_pem.decode()), public_key=public_pem.decode())
54
+ return pair.create_token(
55
+ subject=subject,
56
+ issuer=issuer,
57
+ audience=audience,
58
+ scopes=scopes or [],
59
+ expires_in_seconds=int(hours * 3600),
60
+ )
61
+
62
+
63
+ def main(argv: list[str] | None = None) -> None:
64
+ parser = argparse.ArgumentParser(prog="dataprep-mcp-auth", description=__doc__.split("\n")[0])
65
+ sub = parser.add_subparsers(dest="command", required=True)
66
+
67
+ keys = sub.add_parser("keys", help="create private.pem and public.pem")
68
+ keys.add_argument("--out", type=Path, default=Path("keys"))
69
+
70
+ token = sub.add_parser("token", help="print a signed token for a user")
71
+ token.add_argument("--key", type=Path, default=Path("keys/private.pem"))
72
+ token.add_argument("--subject", required=True, help="user name the server will see")
73
+ token.add_argument("--issuer", default=DEFAULT_ISSUER)
74
+ token.add_argument("--audience", default=DEFAULT_AUDIENCE)
75
+ token.add_argument("--scope", action="append", default=[], help="repeatable")
76
+ token.add_argument("--hours", type=float, default=8)
77
+
78
+ args = parser.parse_args(argv)
79
+ if args.command == "keys":
80
+ private_path, public_path = write_keys(args.out)
81
+ print(f"Wrote {private_path} (keep secret) and {public_path}", file=sys.stderr)
82
+ else:
83
+ print(
84
+ make_token(
85
+ args.key,
86
+ args.subject,
87
+ issuer=args.issuer,
88
+ audience=args.audience,
89
+ scopes=args.scope,
90
+ hours=args.hours,
91
+ )
92
+ )
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
dataprep_mcp/cli.py ADDED
File without changes
File without changes
@@ -0,0 +1,144 @@
1
+ """A minimal AI host: an LLM that uses MCP tools to answer a question.
2
+
3
+ This is what Claude Desktop, VS Code and other hosts do for you:
4
+ 1. Collect the tools from every connected server and describe them to the model.
5
+ 2. Hide tools meant only for app UIs (MCP Apps visibility ["app"]).
6
+ 3. When the model asks for a tool, call it on the right server and return the result.
7
+ 4. Ask the user before running any tool that is not marked read-only.
8
+ 5. Repeat until the model answers in text.
9
+
10
+ The model is behind a small interface, so the loop can be tested with a fake.
11
+ AnthropicLLM is the real one; it needs `pip install anthropic` and ANTHROPIC_API_KEY.
12
+ """
13
+
14
+ import json
15
+ import os
16
+ from collections.abc import Awaitable, Callable
17
+ from dataclasses import dataclass, field
18
+ from typing import Any, Protocol
19
+
20
+ import mcp_types
21
+ from fastmcp.exceptions import ToolError
22
+ from mcp.shared.exceptions import MCPError
23
+
24
+ from dataprep_mcp.client.hub import Hub, is_model_visible, is_read_only
25
+
26
+ MAX_STEPS = 12
27
+ MAX_RESULT_CHARS = 20_000
28
+ DEFAULT_MODEL = os.environ.get("DATAPREP_AGENT_MODEL", "claude-sonnet-5-5")
29
+
30
+ Approve = Callable[[str, dict[str, Any]], Awaitable[bool]]
31
+ Say = Callable[[str], None]
32
+
33
+
34
+ @dataclass
35
+ class ToolCall:
36
+ id: str
37
+ name: str
38
+ arguments: dict[str, Any]
39
+
40
+
41
+ @dataclass
42
+ class Reply:
43
+ text: str
44
+ tool_calls: list[ToolCall] = field(default_factory=list)
45
+ content: list[dict[str, Any]] = field(default_factory=list) # to append to the history
46
+
47
+
48
+ class LLM(Protocol):
49
+ async def respond(self, system: str, messages: list[dict[str, Any]],
50
+ tools: list[dict[str, Any]]) -> Reply: ...
51
+
52
+
53
+ class AnthropicLLM:
54
+ def __init__(self, model: str = DEFAULT_MODEL, max_tokens: int = 4096) -> None:
55
+ try:
56
+ import anthropic
57
+ except ImportError as exc:
58
+ raise RuntimeError("Agent mode needs the Anthropic SDK: pip install anthropic") from exc
59
+ if not os.environ.get("ANTHROPIC_API_KEY"):
60
+ raise RuntimeError("Agent mode needs the ANTHROPIC_API_KEY environment variable.")
61
+ self.client = anthropic.AsyncAnthropic()
62
+ self.model = model
63
+ self.max_tokens = max_tokens
64
+
65
+ async def respond(self, system, messages, tools) -> Reply:
66
+ response = await self.client.messages.create(
67
+ model=self.model, max_tokens=self.max_tokens, system=system,
68
+ tools=tools, messages=messages,
69
+ )
70
+ content = [block.model_dump(exclude_none=True) for block in response.content]
71
+ return Reply(
72
+ text="".join(b["text"] for b in content if b["type"] == "text"),
73
+ tool_calls=[ToolCall(b["id"], b["name"], b["input"])
74
+ for b in content if b["type"] == "tool_use"],
75
+ content=content,
76
+ )
77
+
78
+
79
+ def tool_specs(tools: dict[str, mcp_types.Tool]) -> list[dict[str, Any]]:
80
+ """MCP tool definitions in the shape the model API expects."""
81
+ return [
82
+ {"name": name, "description": tool.description or "", "input_schema": tool.input_schema}
83
+ for name, tool in tools.items()
84
+ if is_model_visible(tool)
85
+ ]
86
+
87
+
88
+ def result_text(result: Any) -> str:
89
+ """Turn a tool result into text for the model: text, links and structured data."""
90
+ parts = []
91
+ for block in result.content:
92
+ if block.type == "text":
93
+ parts.append(block.text)
94
+ elif block.type == "resource_link":
95
+ parts.append(f"[resource] {block.uri} ({block.description or block.name})")
96
+ if result.structured_content is not None:
97
+ parts.append(json.dumps(result.structured_content, default=str))
98
+ text = "\n".join(parts) or "(no content)"
99
+ if len(text) > MAX_RESULT_CHARS:
100
+ text = text[:MAX_RESULT_CHARS] + "\n...(truncated: read the linked resources for detail)"
101
+ return text
102
+
103
+
104
+ def system_prompt(hub: Hub) -> str:
105
+ lines = ["You help the user analyse data using tools from these MCP servers."]
106
+ for server in hub.servers():
107
+ if server.instructions:
108
+ lines.append(f"\nServer '{server.name}': {server.instructions}")
109
+ lines.append("\nTool names start with their server name. Use only facts from tool results.")
110
+ return "\n".join(lines)
111
+
112
+
113
+ async def run_agent(hub: Hub, question: str, llm: LLM, approve: Approve,
114
+ say: Say = print, max_steps: int = MAX_STEPS) -> str:
115
+ tools = await hub.tools()
116
+ specs = tool_specs(tools)
117
+ messages: list[dict[str, Any]] = [{"role": "user", "content": question}]
118
+ system = system_prompt(hub)
119
+
120
+ for _ in range(max_steps):
121
+ reply = await llm.respond(system, messages, specs)
122
+ messages.append({"role": "assistant", "content": reply.content})
123
+ if not reply.tool_calls:
124
+ return reply.text
125
+
126
+ results = []
127
+ for call in reply.tool_calls:
128
+ tool = tools.get(call.name)
129
+ if tool is None or not is_model_visible(tool):
130
+ content, is_error = f"Unknown tool '{call.name}'.", True
131
+ elif not is_read_only(tool) and not await approve(call.name, call.arguments):
132
+ content, is_error = "The user declined this tool call.", True
133
+ else:
134
+ say(f" -> {call.name} {json.dumps(call.arguments)}")
135
+ try:
136
+ result = await hub.call(call.name, call.arguments)
137
+ content, is_error = result_text(result), result.is_error
138
+ except (ToolError, MCPError) as exc: # report it; let the model recover
139
+ content, is_error = str(exc), True
140
+ results.append({"type": "tool_result", "tool_use_id": call.id,
141
+ "content": content, "is_error": is_error})
142
+ messages.append({"role": "user", "content": results})
143
+
144
+ return f"Stopped after {max_steps} steps without a final answer."
@@ -0,0 +1,210 @@
1
+ """An interactive MCP client: connect to several servers and use them by hand,
2
+ or let an LLM use them for you (the 'ask' command).
3
+
4
+ Run: dataprep-client (reads mcp_servers.json in the current folder)
5
+ dataprep-client --config other.json --trace
6
+ """
7
+
8
+ import argparse
9
+ import asyncio
10
+ import json
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from fastmcp.exceptions import ToolError
16
+ from mcp.shared.exceptions import MCPError
17
+
18
+ from dataprep_mcp.client.config import DEFAULT_CONFIG, load_servers
19
+ from dataprep_mcp.client.hub import Hub, is_model_visible, is_read_only
20
+
21
+ HELP = """Commands
22
+ servers connected servers, protocol versions, capabilities
23
+ tools [server] tools (R = read-only, W = changes something, A = app-only)
24
+ call <tool> [json] call a tool, e.g. call dataprep_get_overview {"dataset_id": "ds_1"}
25
+ resources | templates resources and resource templates per server
26
+ read <server> <uri> read a resource, e.g. read dataprep dataset://ds_1/quality
27
+ prompts prompts per server
28
+ prompt <server> <name> [json] show a prompt's messages
29
+ ask <question> let an LLM use the tools (needs ANTHROPIC_API_KEY)
30
+ trace on|off show notifications from servers
31
+ help | quit"""
32
+
33
+ PREVIEW_CHARS = 1500
34
+
35
+
36
+ class Shell:
37
+ def __init__(self, hub: Hub, say=print, ask=input) -> None:
38
+ self.hub = hub
39
+ self.say = say
40
+ self.ask = ask
41
+ self.trace = False
42
+
43
+ def on_notification(self, server: str, message: Any) -> None:
44
+ if self.trace:
45
+ self.say(f" [{server}] {message}")
46
+
47
+ async def progress(self, progress: float, total: float | None, message: str | None) -> None:
48
+ share = f"{progress / total * 100:5.1f}%" if total else f"{progress:g}"
49
+ self.say(f" [{share}] {message or ''}")
50
+
51
+ # ---------- commands ----------
52
+
53
+ async def cmd_servers(self, _: list[str]) -> None:
54
+ for s in self.hub.servers():
55
+ self.say(f"{s.name}: {s.implementation} | protocol {s.protocol_version} | "
56
+ f"{', '.join(s.capabilities)}")
57
+
58
+ async def cmd_tools(self, args: list[str]) -> None:
59
+ for name, tool in (await self.hub.tools()).items():
60
+ server = await self.hub.server_of(name)
61
+ if args and server != args[0]:
62
+ continue
63
+ flags = ("R" if is_read_only(tool) else "W") + ("" if is_model_visible(tool) else "A")
64
+ summary = (tool.description or "").strip().splitlines()[0] if tool.description else ""
65
+ self.say(f" [{flags:<2}] {name}: {summary}")
66
+
67
+ async def cmd_call(self, args: list[str]) -> None:
68
+ if not args:
69
+ raise ValueError("Usage: call <tool> [json arguments]")
70
+ arguments = json.loads(" ".join(args[1:])) if len(args) > 1 else {}
71
+ result = await self.hub.call(args[0], arguments, progress=self.progress)
72
+ self._show_result(result)
73
+
74
+ def _show_result(self, result: Any) -> None:
75
+ if result.is_error:
76
+ self.say("ERROR:")
77
+ for block in result.content:
78
+ if block.type == "text":
79
+ self.say(block.text)
80
+ elif block.type == "resource_link":
81
+ self.say(f" link: {block.uri} ({block.description or block.name})")
82
+ if result.structured_content is not None:
83
+ data = json.dumps(result.structured_content, indent=2, default=str)
84
+ more = f"\n ... ({len(data):,} characters in total)" if len(data) > PREVIEW_CHARS else ""
85
+ self.say(data[:PREVIEW_CHARS] + more)
86
+
87
+ async def cmd_resources(self, _: list[str]) -> None:
88
+ for server, items in (await self.hub.resources()).items():
89
+ for r in items:
90
+ self.say(f" {server}: {r.uri} ({r.mime_type or '?'})")
91
+
92
+ async def cmd_templates(self, _: list[str]) -> None:
93
+ for server, items in (await self.hub.templates()).items():
94
+ for t in items:
95
+ self.say(f" {server}: {t.uri_template}")
96
+
97
+ async def cmd_read(self, args: list[str]) -> None:
98
+ if len(args) != 2:
99
+ raise ValueError("Usage: read <server> <uri>")
100
+ for content in await self.hub.read(args[0], args[1]):
101
+ text = getattr(content, "text", None)
102
+ self.say(f"({content.mime_type})")
103
+ if text is None:
104
+ self.say("(binary content)")
105
+ else:
106
+ more = f"\n ... ({len(text):,} characters)" if len(text) > PREVIEW_CHARS else ""
107
+ self.say(text[:PREVIEW_CHARS] + more)
108
+
109
+ async def cmd_prompts(self, _: list[str]) -> None:
110
+ for server, items in (await self.hub.prompts()).items():
111
+ for p in items:
112
+ names = ", ".join(a.name + ("" if a.required else "?") for a in p.arguments or [])
113
+ self.say(f" {server}: {p.name}({names}) - {p.description or ''}")
114
+
115
+ async def cmd_prompt(self, args: list[str]) -> None:
116
+ if len(args) < 2:
117
+ raise ValueError("Usage: prompt <server> <name> [json arguments]")
118
+ arguments = json.loads(" ".join(args[2:])) if len(args) > 2 else {}
119
+ result = await self.hub.prompt(args[0], args[1], arguments)
120
+ for message in result.messages:
121
+ self.say(f"[{message.role}] {getattr(message.content, 'text', message.content)}")
122
+
123
+ async def cmd_ask(self, args: list[str]) -> None:
124
+ from dataprep_mcp.client.agent import AnthropicLLM, run_agent
125
+
126
+ if not args:
127
+ raise ValueError("Usage: ask <question>")
128
+ llm = AnthropicLLM()
129
+ answer = await run_agent(self.hub, " ".join(args), llm, self.approve, say=self.say)
130
+ self.say("\n" + answer)
131
+
132
+ async def approve(self, tool: str, arguments: dict[str, Any]) -> bool:
133
+ question = f"\nAllow {tool} {json.dumps(arguments)}? It may change something. [y/N] "
134
+ answer = await asyncio.to_thread(self.ask, question)
135
+ return answer.strip().lower() in ("y", "yes")
136
+
137
+ async def cmd_trace(self, args: list[str]) -> None:
138
+ self.trace = bool(args) and args[0] == "on"
139
+ self.say(f"Trace {'on' if self.trace else 'off'}.")
140
+
141
+ async def cmd_help(self, _: list[str]) -> None:
142
+ self.say(HELP)
143
+
144
+ # ---------- dispatch ----------
145
+
146
+ async def handle(self, line: str) -> bool:
147
+ """Run one command line. Returns False when the user wants to quit."""
148
+ line = line.strip()
149
+ if not line:
150
+ return True
151
+ command, _, rest = line.partition(" ")
152
+ if command in ("quit", "exit"):
153
+ return False
154
+ handler = getattr(self, f"cmd_{command}", None)
155
+ if handler is None:
156
+ self.say(f"Unknown command '{command}'. Type 'help'.")
157
+ return True
158
+ # 'ask' takes free text; 'call' and 'prompt' end with free-form JSON.
159
+ if command == "ask":
160
+ args = [rest] if rest else []
161
+ elif command == "call":
162
+ args = rest.split(" ", 1)
163
+ elif command == "prompt":
164
+ args = rest.split(" ", 2)
165
+ else:
166
+ args = rest.split()
167
+ try:
168
+ await handler([a for a in args if a])
169
+ except (ToolError, MCPError, KeyError, ValueError, RuntimeError) as exc:
170
+ self.say(f"Error: {exc}")
171
+ return True
172
+
173
+
174
+ async def run(config: Path, trace: bool) -> None:
175
+ shell: Shell | None = None
176
+
177
+ def relay(server: str, message: Any) -> None:
178
+ if shell is not None:
179
+ shell.on_notification(server, message)
180
+
181
+ hub = Hub.from_config(load_servers(config), on_notification=relay)
182
+ async with hub:
183
+ shell = Shell(hub)
184
+ shell.trace = trace
185
+ await shell.cmd_servers([])
186
+ shell.say("Type 'help' for commands.")
187
+ while True:
188
+ try:
189
+ line = await asyncio.to_thread(input, "\nmcp> ")
190
+ except EOFError:
191
+ break
192
+ if not await shell.handle(line):
193
+ break
194
+
195
+
196
+ def main() -> None:
197
+ parser = argparse.ArgumentParser(description="Interactive client for MCP servers")
198
+ parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
199
+ parser.add_argument("--trace", action="store_true", help="show notifications from servers")
200
+ args = parser.parse_args()
201
+ try:
202
+ asyncio.run(run(args.config, args.trace))
203
+ except (FileNotFoundError, ValueError) as exc:
204
+ sys.exit(f"Error: {exc}")
205
+ except KeyboardInterrupt:
206
+ pass
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
@@ -0,0 +1,48 @@
1
+ """Read an MCP server config file (the same format Claude Desktop uses)."""
2
+
3
+ import json
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from fastmcp.client.transports import StdioTransport, StreamableHttpTransport
10
+
11
+ DEFAULT_CONFIG = Path("mcp_servers.json")
12
+ WINDOWS_SCRIPTS = {"npx": "npx.cmd", "npm": "npm.cmd"} # Node launchers are .cmd files on Windows
13
+
14
+
15
+ def load_servers(path: Path = DEFAULT_CONFIG) -> dict[str, dict[str, Any]]:
16
+ """Return the "mcpServers" section of a config file."""
17
+ if not path.exists():
18
+ raise FileNotFoundError(f"No server config at {path}. Create one (see mcp_servers.json).")
19
+ servers = json.loads(path.read_text(encoding="utf-8")).get("mcpServers", {})
20
+ if not servers:
21
+ raise ValueError(f"{path} has no servers under 'mcpServers'.")
22
+ return servers
23
+
24
+
25
+ def token_for(spec: dict[str, Any]) -> str | None:
26
+ """The bearer token for a remote server: from an env var (preferred) or the file."""
27
+ if "token_env" in spec:
28
+ token = os.environ.get(spec["token_env"], "").strip()
29
+ if not token:
30
+ raise ValueError(f"Environment variable {spec['token_env']} is not set.")
31
+ return token
32
+ return spec.get("token")
33
+
34
+
35
+ def transport_for(spec: dict[str, Any]) -> StdioTransport | StreamableHttpTransport:
36
+ """A stdio transport for a command, or a Streamable HTTP transport for a URL."""
37
+ if "url" in spec:
38
+ return StreamableHttpTransport(
39
+ spec["url"], headers=spec.get("headers"), auth=token_for(spec)
40
+ )
41
+ command = spec["command"]
42
+ if command == "python":
43
+ command = sys.executable # the Python running this client, so the venv is used
44
+ elif os.name == "nt":
45
+ command = WINDOWS_SCRIPTS.get(command, command)
46
+ # Pass the full environment: a server started without PATH cannot find anything.
47
+ env = {**os.environ, **spec.get("env", {})}
48
+ return StdioTransport(command=command, args=spec.get("args", []), env=env, cwd=spec.get("cwd"))
@@ -0,0 +1,94 @@
1
+ """Show any server's form (elicitation request) in the terminal.
2
+
3
+ The client does not know in advance what a server will ask. It reads the
4
+ JSON schema in the request and builds the questions from it: multi-select
5
+ lists, single choices, yes/no, numbers and free text.
6
+ """
7
+
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ Ask = Callable[[str], str]
12
+ Say = Callable[[str], None]
13
+ CANCEL = ":cancel"
14
+
15
+
16
+ class Declined(Exception):
17
+ """The user chose not to answer the form."""
18
+
19
+
20
+ def _options(prop: dict[str, Any]) -> list[tuple[str, str]]:
21
+ """(value, title) pairs from enum, oneOf or anyOf."""
22
+ for key in ("oneOf", "anyOf"):
23
+ if key in prop:
24
+ return [(o["const"], o.get("title", str(o["const"]))) for o in prop[key]]
25
+ if "enum" in prop:
26
+ titles = prop.get("enumNames") or [str(v) for v in prop["enum"]]
27
+ return list(zip(prop["enum"], titles, strict=False))
28
+ return []
29
+
30
+
31
+ def _choose(options: list[tuple[str, str]], ask: Ask, say: Say, multi: bool) -> Any:
32
+ for number, (_, title) in enumerate(options, start=1):
33
+ say(f" {number}. {title}")
34
+ hint = "numbers like 1,3, 'all' or 'none'" if multi else "a number"
35
+ while True:
36
+ answer = ask(f" Choose ({hint}, or {CANCEL}): ").strip().lower()
37
+ if answer == CANCEL:
38
+ raise Declined
39
+ if multi and answer in ("all", "none"):
40
+ return [v for v, _ in options] if answer == "all" else []
41
+ picked = [int(n) for n in answer.replace(" ", "").split(",") if n.isdigit()]
42
+ if picked and all(1 <= n <= len(options) for n in picked) and (multi or len(picked) == 1):
43
+ values = [options[n - 1][0] for n in picked]
44
+ return values if multi else values[0]
45
+ say(" Please enter valid option numbers.")
46
+
47
+
48
+ def _field(name: str, prop: dict[str, Any], required: bool, ask: Ask, say: Say) -> Any:
49
+ title = prop.get("title", name)
50
+ say(f" {title}" + (f": {prop['description']}" if prop.get("description") else ""))
51
+ kind = prop.get("type")
52
+
53
+ if kind == "array":
54
+ return _choose(_options(prop.get("items", {})), ask, say, multi=True)
55
+ options = _options(prop)
56
+ if options:
57
+ return _choose(options, ask, say, multi=False)
58
+
59
+ while True:
60
+ raw = ask(f" {'(required) ' if required else ''}> ").strip()
61
+ if raw == CANCEL:
62
+ raise Declined
63
+ if not raw and not required:
64
+ return prop.get("default")
65
+ try:
66
+ if kind == "boolean":
67
+ if raw.lower() not in ("y", "yes", "n", "no", "true", "false"):
68
+ raise ValueError
69
+ return raw.lower() in ("y", "yes", "true")
70
+ if kind == "integer":
71
+ return int(raw)
72
+ if kind == "number":
73
+ return float(raw)
74
+ if raw:
75
+ return raw
76
+ except ValueError:
77
+ pass
78
+ say(f" Please enter a valid {kind or 'value'}.")
79
+
80
+
81
+ def fill_form(message: str, schema: dict[str, Any], ask: Ask = input, say: Say = print
82
+ ) -> dict[str, Any] | None:
83
+ """Ask every question in the schema. Returns the answers, or None if declined."""
84
+ say("\n" + "=" * 70 + "\nTHE SERVER IS ASKING FOR YOUR INPUT\n" + "=" * 70)
85
+ say(message)
86
+ required = set(schema.get("required", []))
87
+ answers: dict[str, Any] = {}
88
+ try:
89
+ for name, prop in schema.get("properties", {}).items():
90
+ answers[name] = _field(name, prop, name in required, ask, say)
91
+ except Declined:
92
+ say(" Declined.")
93
+ return None
94
+ return answers