Skip to content
Back to search

mcp2py

Turn any MCP server into a Python module

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/maximerivest--mcp2py/badge.svg)](/listings/maximerivest--mcp2py)

HTML

<a href="/listings/maximerivest--mcp2py"><img src="/api/listings/maximerivest--mcp2py/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

**1. Install**

You can install mcp2py via pip:

pip install mcp2py

Python has had the pesky problem of not having a standard way to manage dependencies for a long time. To avoid dependency conflicts, it is recommended to use virtual environments. My favorite way to do this is with `uv` (see here: https://docs.astral.sh/uv/getting-started/installation/). Then you can create a new environment and install mcp2py like this:

# Install uv (if you haven't already)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Create a new project with a virtual environment
uv init my-mcp-project
cd my-mcp-project

# Install mcp2py
uv add mcp2py

# Activate the environment and start coding
uv run python

**2. Use it**

from mcp2py import load

# Load any MCP server with OAuth authentication
notion = load("https://mcp.notion.com/mcp", auth="oauth")

# Browser opens automatically for OAuth login
# Once authenticated, you can use the tools

notion.notion_get_self()

**3. That’s it!**

The server runs as a subprocess, tools are Python methods, everything just works.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,384 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # mcp2py: Turn any MCP server into a python module
  2. MCP (Model Context Protocol) is an emerging standard for AI tools and
  3. resources. The standard is compatible with normal REST API servers, but
  4. adds extra metadata to describe tools, resources, and prompts in a
  5. machine-readable way. This provides us with a great opportunity to
  6. create Python modules that completely and automatically map to these MCP
  7. servers. The biggest advantage of this approach is that we can use any
  8. MCP server as if it were a native Python library, with zero
  9. configuration. This can be quite a big deal as creating Python software
  10. development kits that map to REST APIs is extremely common and was quite
  11. a manual process. Now, if the organization hosting the REST API also
  12. provides an MCP interface, we can automatically generate a Python SDK
  13. for it with zero effort! Don’t worry if this is not all clear to you.
  14. You can still leverage the power of mcp2py without knowing all the
  15. details of MCP. All you need to know is: if you want to programmatically
  16. interact with a website, it is likely that they have an API and as time
  17. goes on it is very likely that they have an MCP interface for that API.
  18. If they do, you don’t have to learn a whole set of web programming
  19. skills, you can just use mcp2py to load the MCP server and start calling
  20. functions right away as if it were a native Python library!
  21. Another cool thing to note is that servers don’t have to be running
  22. remotely. You can (and have) a lot of servers running on your own
  23. personal computer right now. This is useful to have different programs,
  24. possibly in different programming languages, talking to each other. As
  25. apps that you install will more and more open up a small local server on
  26. your machine to let LLMs interact with them, you will also be able to
  27. leverage mcp2py to interact with these local servers. That could look
  28. like Slack opening a server that lets you query your messages. If so,
  29. you could then use mcp2py and have a Python module (a library in
  30. essence) that lets you query your Slack messages directly from Python.
  31. Super powerful!
  32. ## Overview
  33. Here is a very simple example of using mcp2py to interact with your
  34. local filesystem. That is not very useful as you could just use the
  35. built-in Python libraries to do that, but it serves as a very simple
  36. example to illustrate how mcp2py works. In this snippet of code we use
  37. load to both start the MCP server (which is a Node.js server in this
  38. case) and connect to it. Once connected we can call the list_directory
  39. tool as if it were a native Python function:
  40. ``` python
  41. from mcp2py import load
  42. fstools = load("npx -y @modelcontextprotocol/server-filesystem /home")
  43. fstools.list_directory("/home")
  44. ```
  45. [DIR] maxime
  46. This is similar to using the os library in Python:
  47. ``` python
  48. import os
  49. os.listdir("/home")
  50. ```
  51. ['maxime']
  52. The main difference is that instead of going directly from Python to the
  53. system, we send commands to a local Node (JavaScript) server and that
  54. server has some ‘security’ features. For example, we are not allowed to
  55. search outside of /home because that is what we have set as the root.
  56. Those features are very useful when you want to expose your file system
  57. to an LLM.
  58. ------------------------------------------------------------------------
  59. ## Quick Start
  60. **1. Install**
  61. You can install mcp2py via pip:
  62. ``` bash
  63. pip install mcp2py
  64. ```
  65. Python has had the pesky problem of not having a standard way to manage
  66. dependencies for a long time. To avoid dependency conflicts, it is
  67. recommended to use virtual environments. My favorite way to do this is
  68. with `uv` (see here:
  69. https://docs.astral.sh/uv/getting-started/installation/). Then you can
  70. create a new environment and install mcp2py like this:
  71. ``` bash
  72. # Install uv (if you haven't already)
  73. curl -LsSf https://astral.sh/uv/install.sh | sh
  74. # Create a new project with a virtual environment
  75. uv init my-mcp-project
  76. cd my-mcp-project
  77. # Install mcp2py
  78. uv add mcp2py
  79. # Activate the environment and start coding
  80. uv run python
  81. ```
  82. **2. Use it**
  83. ``` python
  84. from mcp2py import load
  85. # Load any MCP server with OAuth authentication
  86. notion = load("https://mcp.notion.com/mcp", auth="oauth")
  87. # Browser opens automatically for OAuth login
  88. # Once authenticated, you can use the tools
  89. notion.notion_get_self()
  90. ```
  91. **3. That’s it!**
  92. The server runs as a subprocess, tools are Python methods, everything
  93. just works.
  94. ## What is MCP?
  95. MCP servers expose **tools**, **resources**, and **prompts** via a
  96. protocol. mcp2py turns them into {python}:
  97. - 🔧 **Tools** → {python} functions
  98. - 📦 **Resources** → {python} constants/attributes
  99. - 📝 **Prompts** → Template functions/strings
  100. ## Philosophy
  101. **It Just Works™ - But You Can Customize Everything**
  102. mcp2py is designed for **researchers, data analysts, and {python}
  103. beginners** who want to try MCP servers without complexity. At the same
  104. time, it provides **full control** for developers building production
  105. applications.
  106. **Zero configuration by default:** - OAuth login? Browser opens
  107. automatically - Need user input? Terminal prompts appear - Server needs
  108. an LLM? We handle it - Everything “just works” out of the box
  109. **No ceiling for advanced users:** - Override any default behavior -
  110. Customize auth flows - Build production apps - Full control when you
  111. need it
  112. **Your {python} REPL/code becomes an MCP client.** The server is a
  113. separate process (Node.js, {python}, whatever) that mcp2py communicates
  114. with via JSON-RPC. Your {python} code can: - Call tools (server
  115. functions) as if they’re local {python} functions - Access resources
  116. (server data) as {python} attributes - Handle server requests (sampling,
  117. elicitation) automatically or via custom callbacks - Work seamlessly
  118. with any AI SDK (Anthropic, OpenAI, DSPy, etc.)
  119. ## Getting Started
  120. ### For Beginners & Researchers: It Just Works
  121. ``` python
  122. from mcp2py import load
  123. # Load any MCP server - that's it!
  124. server = load("https://api.example.com/mcp")
  125. # If it needs login:
  126. # → Browser opens automatically
  127. # → You log in once
  128. # → Browser closes
  129. # → Done!
  130. # If it needs your input:
  131. # → Nice terminal prompts appear
  132. # → You answer
  133. # → Code continues!
  134. # If it needs AI help (sampling):
  135. # → Uses your ANTHROPIC_API_KEY or OPENAI_API_KEY
  136. # → Handles it automatically
  137. # → You don't even notice!
  138. # Just use the tools!
  139. result = server.analyze_data(dataset="sales_2024.csv")
  140. print(result)
  141. ```
  142. **That’s it. No configuration. No setup. It just works.**
  143. ------------------------------------------------------------------------
  144. ## Interface Design
  145. ### Basic Usage
  146. ``` python
  147. from mcp2py import load
  148. # Load an MCP server - simple and clean
  149. weather = load("npx -y @h1deya/mcp-server-weather")
  150. # Or from a remote HTTP server (SSE/HTTP Stream transport)
  151. api = load("https://api.example.com/mcp")
  152. # With authentication
  153. api = load("https://api.example.com/mcp", headers={"Authorization": "Bearer YOUR_TOKEN"})
  154. # Or from a {python} script
  155. travel = load("{python} my_mcp_server.py")
  156. # Tools become functions
  157. alerts = weather.get_alerts(state="CA")
  158. forecast = weather.get_forecast(latitude=37.7749, longitude=-122.4194)
  159. print(forecast)
  160. # Resources become attributes
  161. print(weather.API_DOCUMENTATION) # Constant resource
  162. print(weather.current_config) # Dynamic resource
  163. # Prompts become template functions
  164. prompt = weather.create_weather_report(location="NYC", style="casual")
  165. ```
  166. ### Use with AI Frameworks (DSPy, Claudette, etc.)
  167. **The `.tools` attribute gives you a list of callable {python}
  168. functions**:
  169. ``` python
  170. from mcp2py import load
  171. server = load("npx -y @modelcontextprotocol/server-filesystem /tmp")
  172. # Get tools as callable functions
  173. tools = server.tools
  174. # [<function read_file>, <function write_file>, ...]
  175. # Each function has __name__ and __doc__
  176. print(tools[0].__name__) # "read_file"
  177. print(tools[0].__doc__) # "Read a file from the filesystem"
  178. # And they're callable!
  179. result = tools[0](path="/tmp/test.txt")
  180. ```
  181. ### Working with AI Frameworks
  182. The `.tools` attribute gives you callable functions ready for frameworks
  183. like DSPy and Claudette:
  184. ``` python
  185. from mcp2py import load
  186. import dspy
  187. # Load MCP server
  188. travel = load("{python} airline_server.py")
  189. # Use with DSPy - pass callable functions directly
  190. class CustomerService(dspy.Signature):
  191. user_request: str = dspy.InputField()
  192. result: str = dspy.OutputField()
  193. dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
  194. # Pass tools directly to DSPy (it expects callables)
  195. react = dspy.ReAct(CustomerService, tools=travel.tools)
  196. result = react(user_request="Book a flight from SFO to JFK on 09/01/2025")
  197. print(result)
  198. ```
  199. ``` python
  200. # Also works with Claudette
  201. from mcp2py import load
  202. from claudette import Chat
  203. weather = load("npx -y @h1deya/mcp-server-weather")
  204. # Claudette expects callable functions
  205. chat = Chat(model="claude-3-5-sonnet-20241022", tools=weather.tools)
  206. response = chat("What's the weather in Tokyo?")
  207. # Claudette automatically calls the tools as needed
  208. print(response)
  209. ```
  210. **Note:** For SDKs that have native MCP support (Anthropic, OpenAI,
  211. Google Gemini), use their built-in MCP integration directly. The
  212. `.tools` attribute is for frameworks like DSPy and Claudette that expect
  213. {python} callables.
  214. ### Type Safety & IDE Support
  215. **Auto-generated stubs for perfect autocomplete:**
  216. ``` python
  217. from mcp2py import load
  218. # Stubs auto-generated to ~/.cache/mcp2py/stubs/
  219. server = load("npx my-server")
  220. # IDE now has full autocomplete and type hints!
  221. server.search_files(
  222. pattern="*.py", # type: str - IDE knows this!
  223. max_results=10 # type: int, optional - IDE suggests this!
  224. ) # Returns: dict[str, Any] - IDE shows return type!
  225. ```
  226. **Manual stub generation:**
  227. ``` python
  228. # Generate stub to specific location for your project
  229. server = load("npx weather-server")
  230. server.generate_stubs("./stubs/weather.pyi")
  231. # Or let it auto-cache (default behavior)
  232. # Stubs saved to: ~/.cache/mcp2py/stubs/<command_hash>.pyi
  233. ```
  234. **How it works:** - `load()` returns a **dynamically typed class** with
  235. all methods pre-defined - Your IDE sees proper type hints immediately -
  236. **no configuration needed!** - Type hints include parameter names,
  237. types, defaults, and return types - Works in VS Code, PyCharm, Jupyter
  238. notebooks, and any {python} IDE - Also generates `.pyi` stub files to
  239. `~/.cache/mcp2py/stubs/` for reference
  240. **Zero configuration required** - autocomplete just works! ✨
  241. ## MCP Client Features
  242. When your {python} code acts as an MCP client, servers may request these
  243. capabilities:
  244. ### **Sampling**
  245. When a server needs LLM completions, mcp2py handles it automatically.
  246. **Default: Works Out of the Box**
  247. ``` python
  248. from mcp2py import load
  249. # Just works! Uses your default LLM
  250. server = load("npx travel-server")
  251. # If server needs LLM help, mcp2py:
  252. # 1. Checks for ANTHROPIC_API_KEY or OPENAI_API_KEY in environment
  253. # 2. Calls the LLM automatically
  254. # 3. Returns result to server
  255. # 4. Your code continues!
  256. result = server.book_flight(destination="Tokyo")
  257. ```
  258. **Configure your preferred LLM:**
  259. ``` python
  260. # Set via environment (recommended)
  261. import os
  262. os.environ["ANTHROPIC_API_KEY"] = "sk-..."
  263. # Or configure globally using LiteLLM model strings
  264. from mcp2py import configure
  265. configure(
  266. model="claude-3-5-sonnet-20241022" # or "gpt-4o", "gemini/gemini-pro", etc.
  267. )
  268. # LiteLLM automatically detects the right API based on model name
  269. # Uses standard env vars: ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.
  270. # Now all servers use this LLM for sampling
  271. server = load("npx travel-server")
  272. ```
  273. **Advanced: Custom Sampling Handler**
  274. ``` python
  275. from mcp2py import load
  276. def my_sampling_handler(messages, model_prefs, system_prompt, max_tokens):
  277. """Full control over LLM calls."""
  278. import anthropic
  279. client = anthropic.Anthropic()
  280. response = client.messages.create(
  281. model="claude-3-5-sonnet-20241022",
  282. messages=messages,
  283. max_tokens=max_tokens
  284. )
  285. return response.content[0].text
  286. server = load(
  287. "npx travel-server",
  288. on_sampling=my_sampling_handler # Override default
  289. )
  290. ```
  291. **Disable sampling (for security/cost control):**
  292. ``` python
  293. server = load(
  294. "npx travel-server",
  295. allow_sampling=False # Raises error if server requests LLM
  296. )
  297. ```
  298. ### **Elicitation**
  299. When a server needs user input, mcp2py prompts automatically.
  300. **Default: Terminal Prompts**
  301. ``` python
  302. from mcp2py import load
  303. # Just works! Terminal prompts appear automatically
  304. server = load("npx travel-server")
  305. # Server asks: "Confirm booking for $500?"
  306. # Terminal shows:
  307. #
  308. # Server asks: Confirm booking for $500?
  309. # confirm_booking (boolean): y/n
  310. #
  311. # You type: y
  312. # Code continues!
  313. result = server.book_flight(destination="Paris")
  314. ```
  315. **What you see:**
  316. Calling book_flight...
  317. ┌─────────────────────────────────────────┐
  318. │ 🔔 Server needs your input │
  319. ├─────────────────────────────────────────┤
  320. │ Confirm booking for $500? │
  321. │ │
  322. │ confirm_booking (boolean): y/n │
  323. │ seat_preference (window/aisle/middle): │
  324. │ meal_preference (optional): │
  325. └─────────────────────────────────────────┘
  326. > y
  327. > window
  328. > vegetarian
  329. Booking confirmed!
  330. **Advanced: Custom Elicitation Handler**
  331. ``` python
  332. from mcp2py import load
  333. def my_input_handler(message, schema):
  334. """Custom UI for user input."""
  335. # Build a GUI, web form, voice input, etc.
  336. from tkinter import simpledialog
  337. return simpledialog.askstring("Server Request", message)
  338. server = load(
  339. "npx travel-server",
  340. on_elicitation=my_input_handler
  341. )
  342. ```
  343. **Disable elicitation (for automated scripts):**
  344. ``` python
  345. server = load(
  346. "npx travel-server",
  347. allow_elicitation=False # Raises error if server asks for input
  348. )
  349. # Or provide pre-filled answers
  350. server = load(
  351. "npx travel-server",
  352. elicitation_defaults={
  353. "confirm_booking": True,
  354. "seat_preference": "window"
  355. }
  356. )
  357. ```
  358. ### **Roots**
  359. Servers can ask which directories to focus on. Optional, simple:
  360. ``` python
  361. # Single directory
  362. server = load("npx filesystem-server", roots="/home/user/projects")
  363. # Multiple directories
  364. server = load(
  365. "npx filesystem-server",
  366. roots=["/home/user/projects", "/tmp/workspace"]
  367. )
  368. # Update roots dynamically
  369. server.set_roots(["/home/user/new-project"])
  370. ```
  371. ## Design Rules
  372. ### 1. **Tools → Functions**
  373. MCP tools map to {python} functions with full support for:
  374. - **Arguments**: Both required and optional parameters
  375. - **Type hints**: Generated from JSON Schema `inputSchema`
  376. - **Docstrings**: Built from tool `description`
  377. - **Return types**: Typed as `dict[str, Any]` (MCP tools return JSON)
  378. **Naming convention**: Snake_case (MCP `getWeather` → {python}
  379. `get_weather`)
  380. ``` python
  381. # MCP Tool Definition:
  382. # {
  383. # "name": "searchFiles",
  384. # "description": "Search for files matching a pattern",
  385. # "inputSchema": {
  386. # "type": "object",
  387. # "properties": {
  388. # "pattern": {"type": "string", "description": "Glob pattern"},
  389. # "maxResults": {"type": "integer", "default": 100}
  390. # },
  391. # "required": ["pattern"]
  392. # }
  393. # }
  394. # Generated {python}:
  395. def search_files(pattern: str, max_results: int = 100) -> dict[str, Any]:
  396. """Search for files matching a pattern.
  397. Args:
  398. pattern: Glob pattern
  399. max_results: Maximum results to return (default: 100)
  400. """
  401. ...
  402. ```
  403. ### 2. **Resources → Constants or Properties**
  404. Resources map differently based on their nature:
  405. - **Static resources** (like documentation, schemas): Module-level
  406. constants (UPPER_CASE)
  407. - **Dynamic resources** (may change): Properties with getters
  408. (lowercase)
  409. ``` python
  410. # Static resource (cached)
  411. API_DOCS: str = server._get_resource("api://docs")
  412. # Dynamic resource (fetched on access)
  413. @property
  414. def current_status() -> dict[str, Any]:
  415. """Current server status."""
  416. return server._get_resource("status://current")
  417. ```
  418. **Naming convention**: - Static: `UPPER_SNAKE_CASE` - Dynamic:
  419. `lower_snake_case` properties
  420. ### 3. **Prompts → Template Functions**
  421. Prompts become functions that return formatted strings:
  422. ``` python
  423. # MCP Prompt:
  424. # {
  425. # "name": "reviewCode",
  426. # "description": "Generate a code review prompt",
  427. # "arguments": [
  428. # {"name": "code", "description": "Code to review", "required": true},
  429. # {"name": "focus", "description": "Review focus area", "required": false}
  430. # ]
  431. # }
  432. # Generated {python}:
  433. def review_code(code: str, focus: str | None = None) -> str:
  434. """Generate a code review prompt.
  435. Args:
  436. code: Code to review
  437. focus: Review focus area (optional)
  438. Returns:
  439. Formatted prompt string ready for LLM
  440. """
  441. ...
  442. ```
  443. ### 4. **Error Handling**
  444. {python}ic exceptions for common failures:
  445. ``` python
  446. from mcp2py.exceptions import (
  447. MCPConnectionError, # Can't connect to server
  448. MCPToolError, # Tool execution failed
  449. MCPResourceError, # Resource not found
  450. MCPValidationError, # Invalid arguments
  451. )
  452. try:
  453. result = server.expensive_operation(data=large_data)
  454. except MCPValidationError as e:
  455. print(f"Invalid input: {e}")
  456. except MCPToolError as e:
  457. print(f"Tool failed: {e}")
  458. ```
  459. ### 5. **Async Support**
  460. Use `aload()` for async MCP servers:
  461. ``` python
  462. from mcp2py import aload
  463. # Async version - all tools become async
  464. server = await aload("npx async-server")
  465. result = await server.fetch_data(url="https://example.com")
  466. status = await server.get_current_status()
  467. ```
  468. ### 6. **Context Managers**
  469. Automatic cleanup when using `with`:
  470. ``` python
  471. from mcp2py import load
  472. # Sync version
  473. with load("npx my-server") as server:
  474. result = server.do_work()
  475. # Server process automatically terminated
  476. # Async version
  477. async with aload("npx my-server") as server:
  478. result = await server.do_work()
  479. ```
  480. ## Configuration
  481. ### Server Registry (Optional)
  482. Register commonly-used servers once, then load by name:
  483. ``` python
  484. from mcp2py import register, load
  485. # Register servers (run once, e.g., in your setup script)
  486. register(
  487. weather="npx -y @h1deya/mcp-server-weather",
  488. brave="npx -y brave-search-mcp-server",
  489. filesystem="npx -y @modelcontextprotocol/server-filesystem /tmp",
  490. myserver="{python} my_mcp_server.py"
  491. )
  492. # Then load by name anywhere
  493. weather = load("weather")
  494. brave = load("brave")
  495. # Or use commands directly (no registration needed)
  496. custom = load("npx my-custom-server")
  497. ```
  498. Registry is saved to `~/.config/mcp2py/servers.json` automatically.
  499. ### Remote Servers & Authentication
  500. MCP servers can be hosted remotely over HTTP (using SSE or HTTP Stream
  501. transport):
  502. ``` python
  503. from mcp2py import load, register
  504. # Connect to remote MCP server
  505. api = load("https://api.example.com/mcp")
  506. # With Bearer token authentication
  507. secure_api = load(
  508. "https://api.example.com/mcp",
  509. headers={"Authorization": "Bearer sk-1234567890"}
  510. )
  511. # With custom headers (API keys, etc.)
  512. custom_api = load(
  513. "https://api.example.com/mcp",
  514. headers={
  515. "X-API-Key": "your-api-key",
  516. "X-Client-ID": "your-client-id"
  517. }
  518. )
  519. # Register remote servers too
  520. register(
  521. production_api="https://api.prod.example.com/mcp",
  522. staging_api="https://api.staging.example.com/mcp"
  523. )
  524. # Load with auth at runtime
  525. prod = load("production_api", headers={"Authorization": f"Bearer {get_token()}"})
  526. ```
  527. **Use cases for remote MCP servers:** - Company-hosted internal tools -
  528. Paid API services via MCP - Shared team resources (databases, analytics,
  529. etc.) - Cloud-based AI tool marketplaces
  530. ### OAuth Authentication (Google, GitHub, etc.)
  531. **Default: Zero Configuration (For beginners, researchers, data
  532. analysts)**
  533. mcp2py handles OAuth automatically - just load and go:
  534. ``` python
  535. from mcp2py import load
  536. # That's it! Browser opens, you log in, then continue coding
  537. server = load("https://api.example.com/mcp")
  538. # First tool call triggers OAuth if needed:
  539. # 1. Browser window pops up
  540. # 2. You log in (Google/GitHub/etc.)
  541. # 3. Window closes automatically
  542. # 4. Your code continues!
  543. result = server.my_tool() # Works immediately after login
  544. ```
  545. **What happens under the hood:** - mcp2py detects OAuth requirement (401
  546. response) - Discovers OAuth endpoints automatically - Opens browser for
  547. login (PKCE-secured) - Stores tokens in `~/.config/mcp2py/tokens.json` -
  548. Refreshes tokens automatically when they expire
  549. **You never think about tokens.**
  550. ------------------------------------------------------------------------
  551. **Advanced: Custom OAuth (For production apps)**
  552. Override defaults when building applications:
  553. ``` python
  554. from mcp2py import load
  555. # Option 1: Custom token provider
  556. def get_google_token():
  557. """Your custom OAuth logic."""
  558. from google.oauth2.credentials import Credentials
  559. # Your implementation here
  560. return creds.token
  561. server = load(
  562. "https://api.example.com/mcp",
  563. auth=get_google_token # Called when token needed
  564. )
  565. # Option 2: Service account (no browser)
  566. from google.oauth2 import service_account
  567. credentials = service_account.Credentials.from_service_account_file(
  568. 'service-account.json'
  569. )
  570. server = load(
  571. "https://api.example.com/mcp",
  572. auth=credentials
  573. )
  574. # Option 3: Manual token management
  575. server = load(
  576. "https://api.example.com/mcp",
  577. headers={"Authorization": f"Bearer {your_token}"}
  578. )
  579. # Option 4: Disable auto-browser (for servers/CI)
  580. server = load(
  581. "https://api.example.com/mcp",
  582. auto_auth=False # Raises error instead of opening browser
  583. )
  584. ```
  585. **Environment variable support (for production):**
  586. ``` bash
  587. # Set token via environment
  588. export MCP_TOKEN="your-token-here"
  589. ```
  590. ``` python
  591. # Automatically used if available
  592. server = load("https://api.example.com/mcp")
  593. ```
  594. ### Security Considerations
  595. **Client-Side (mcp2py handles automatically):** - ✅ Secure token
  596. storage - OAuth tokens cached in `~/.fastmcp/oauth-mcp-client-cache/` -
  597. ✅ PKCE support for OAuth flows (Proof Key for Code Exchange) - ✅
  598. Automatic token refresh before expiration - ✅ Environment variable
  599. support (`MCP_TOKEN`)
  600. **Server-Side (your responsibility when connecting):** - Use HTTPS URLs
  601. for production servers (not HTTP) - Ensure the MCP servers you connect
  602. to implement proper authentication - Rotate tokens/credentials
  603. regularly - Never commit tokens to version control
  604. **Best Practices:**
  605. ``` python
  606. # Good: Use environment variables
  607. import os
  608. server = load("https://api.example.com/mcp", auth=os.getenv("MCP_TOKEN"))
  609. # Good: HTTPS for production
  610. server = load("https://api.example.com/mcp", auth="oauth")
  611. # Avoid: Hardcoded tokens in code
  612. # server = load("https://api.example.com/mcp", auth="sk-secret-123") # Don't do this!
  613. ```
  614. ## Advanced Features
  615. ### Stub Generation
  616. Stubs are automatically generated when you use `load()`. They’re cached
  617. to `~/.cache/mcp2py/stubs/` for reuse.
  618. **Programmatic API:**
  619. ``` python
  620. from mcp2py import load
  621. # Stubs auto-generated on load
  622. server = load("npx weather-server")
  623. # Generate to specific path
  624. stub_path = server.generate_stubs("./stubs/weather.pyi")
  625. print(f"Stub saved to: {stub_path}")
  626. # Check cache location
  627. from mcp2py.stubs import get_stub_cache_path
  628. cache_path = get_stub_cache_path("npx weather-server")
  629. print(f"Cached at: {cache_path}")
  630. ```
  631. ### Complete Client Example
  632. ``` python
  633. """Full example of {python} as MCP client with all features."""
  634. from mcp2py import load
  635. import anthropic
  636. # Setup callbacks for server requests
  637. def handle_sampling(messages, model_prefs, system_prompt, max_tokens):
  638. """Server wants LLM completion."""
  639. client = anthropic.Anthropic()
  640. response = client.messages.create(
  641. model="claude-3-5-sonnet-20241022",
  642. messages=messages,
  643. system=system_prompt,
  644. max_tokens=max_tokens
  645. )
  646. return response.content[0].text
  647. def handle_elicitation(message, schema):
  648. """Server needs user input."""
  649. print(f"\n🔔 Server asks: {message}")
  650. if schema.get("type") == "string":
  651. return input("→ ")
  652. if schema.get("type") == "boolean":
  653. return input("→ (y/n): ").lower() in ["y", "yes", "true"]
  654. if schema.get("type") == "object":
  655. result = {}
  656. for prop, details in schema.get("properties", {}).items():
  657. result[prop] = input(f" {prop} ({details.get('description', '')}): ")
  658. return result
  659. import json
  660. return json.loads(input("→ (JSON): "))
  661. # Connect to server with all features
  662. server = load(
  663. "npx travel-booking-server",
  664. on_sampling=handle_sampling,
  665. on_elicitation=handle_elicitation,
  666. roots="/home/user/travel-docs"
  667. )
  668. # Use the server - callbacks invoked automatically when needed
  669. booking = server.book_flight(destination="Barcelona", dates="June 15-22")
  670. print(booking)
  671. ```
  672. ### Inspection
  673. ``` python
  674. from mcp2py import load
  675. server = load("npx my-server")
  676. # List all available tools
  677. print(server.tools) # List of tool schemas for AI SDKs
  678. # Get tool info
  679. print(server.get_weather.__doc__)
  680. print(server.get_weather.__signature__)
  681. # List resources
  682. print(server.resources)
  683. # List prompts
  684. print(server.prompts)
  685. ```
  686. ### Middleware & Hooks
  687. ``` python
  688. from mcp2py import load
  689. def log_tool_calls(tool_name: str, args: dict, result: dict):
  690. print(f"Called {tool_name} with {args} → {result}")
  691. server = load(
  692. "npx my-server",
  693. on_tool_call=log_tool_calls,
  694. timeout=30.0
  695. )
  696. ```
  697. ## Implementation Priorities
  698. ### Phase 1: Core Functionality
  699. 1. `load()` function with stdio transport
  700. 2. Tool → function mapping with type hints
  701. 3. Simple resource access
  702. 4. Prompt → template function mapping
  703. 5. `.tools` attribute for AI SDK integration
  704. ### Phase 2: Developer Experience
  705. 1. Stub generation for IDE support
  706. 2. Server registry (`~/.config/mcp2py/servers.json`)
  707. 3. Context manager protocol
  708. 4. Better error messages and exceptions
  709. ### Phase 3: Advanced Features
  710. 1. `aload()` for async support
  711. 2. SSE transport for HTTP servers
  712. 3. Middleware/hooks system
  713. 4. Sampling and elicitation callbacks
  714. ## Design Principles
  715. 1. **Delightful Defaults**: Authentication, sampling, elicitation all
  716. work automatically
  717. 2. **No Ceiling**: Every default can be overridden for production use
  718. cases
  719. 3. **Beginner-Friendly**: Data analysts and researchers can start
  720. immediately
  721. 4. **Production-Ready**: Full control for developers building apps
  722. 5. **Progressive Disclosure**: Simple by default, powerful when you
  723. need it
  724. 6. **Type Safety**: Generate types wherever possible for IDE support
  725. 7. **{python}ic**: Convert MCP conventions to {python} conventions
  726. automatically
  727. 8. **Clear Errors**: Helpful messages when things go wrong, with
  728. suggestions
  729. ## Complete Examples
  730. ### Example 1: Synchronous - Weather Analysis with DSPy
  731. ``` python
  732. #!/usr/bin/env {python}3
  733. """Analyze weather alerts using DSPy and MCP."""
  734. from mcp2py import load
  735. import dspy
  736. # Configure DSPy
  737. dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
  738. # Load MCP weather server
  739. weather = load("npx -y @h1deya/mcp-server-weather")
  740. # Define DSPy signature
  741. class WeatherAnalyzer(dspy.Signature):
  742. """Analyze weather alerts and provide recommendations."""
  743. state: str = dspy.InputField()
  744. analysis: str = dspy.OutputField(desc="Weather analysis and travel recommendations")
  745. # Create agent with MCP tools
  746. agent = dspy.ReAct(WeatherAnalyzer, tools=weather.tools)
  747. # Analyze weather for multiple states
  748. states = ["CA", "NY", "TX", "FL"]
  749. for state in states:
  750. # Agent automatically calls weather.get_alerts() and weather.get_forecast()
  751. result = agent(state=state)
  752. print(f"\n{state}:")
  753. print(result.analysis)
  754. ```
  755. ### Example 2: Asynchronous - Travel Booking System
  756. ``` python
  757. #!/usr/bin/env {python}3
  758. """Async travel booking system with MCP and Anthropic."""
  759. import asyncio
  760. from mcp2py import aload
  761. import anthropic
  762. async def book_trip(user_request: str):
  763. """Book a trip using MCP travel server and Claude."""
  764. # Load async MCP server
  765. travel = await aload("{python} travel_server.py")
  766. # Setup Anthropic client
  767. client = anthropic.Anthropic()
  768. # Initial request to Claude with MCP tools
  769. response = client.messages.create(
  770. model="claude-3-5-sonnet-20241022",
  771. max_tokens=2048,
  772. tools=travel.tools, # MCP tools passed to Claude
  773. messages=[{"role": "user", "content": user_request}]
  774. )
  775. # Handle tool calls in a loop
  776. messages = [{"role": "user", "content": user_request}]
  777. while response.stop_reason == "tool_use":
  778. # Extract tool calls from response
  779. tool_results = []
  780. for content_block in response.content:
  781. if content_block.type == "tool_use":
  782. # Call MCP tool asynchronously
  783. tool_name = content_block.name
  784. tool_args = content_block.input
  785. print(f"Calling {tool_name}({tool_args})...")
  786. # Execute tool via MCP
  787. tool_func = getattr(travel, tool_name)
  788. result = await tool_func(**tool_args)
  789. tool_results.append({
  790. "type": "tool_result",
  791. "tool_use_id": content_block.id,
  792. "content": str(result)
  793. })
  794. # Add assistant response and tool results to conversation
  795. messages.append({"role": "assistant", "content": response.content})
  796. messages.append({"role": "user", "content": tool_results})
  797. # Continue conversation
  798. response = client.messages.create(
  799. model="claude-3-5-sonnet-20241022",
  800. max_tokens=2048,
  801. tools=travel.tools,
  802. messages=messages
  803. )
  804. # Extract final response
  805. return response.content[0].text
  806. async def main():
  807. result = await book_trip(
  808. "Book a round-trip flight from SFO to JFK on Sept 1-8, 2025. "
  809. "My name is Adam Smith. I prefer window seats and morning flights."
  810. )
  811. print("\n" + "="*60)
  812. print("BOOKING RESULT:")
  813. print("="*60)
  814. print(result)
  815. if __name__ == "__main__":
  816. asyncio.run(main())
  817. ```
  818. ### Example 3: Simple Synchronous - Direct Tool Calls
  819. ``` python
  820. #!/usr/bin/env {python}3
  821. """Simple weather check without AI - just direct MCP tool calls."""
  822. from mcp2py import load
  823. # Load weather server
  824. weather = load("npx -y @h1deya/mcp-server-weather")
  825. # Direct tool calls (no LLM needed)
  826. print("Weather Alerts for California:")
  827. alerts = weather.get_alerts(state="CA")
  828. print(alerts)
  829. print("\nSan Francisco Forecast:")
  830. forecast = weather.get_forecast(latitude=37.7749, longitude=-122.4194)
  831. print(forecast)
  832. # MCP tools are just {python} functions!
  833. ```
  834. ## Testing with Real Servers
  835. Here are **real MCP servers you can test right now**:
  836. ``` python
  837. from mcp2py import load
  838. # Weather server (Node.js via npx)
  839. weather = load("npx -y @h1deya/mcp-server-weather")
  840. # Brave search (requires API key)
  841. brave = load("npx -y brave-search-mcp-server")
  842. # Filesystem operations
  843. fs = load("npx -y @modelcontextprotocol/server-filesystem /tmp")
  844. # Memory/knowledge graph
  845. memory = load("npx -y @modelcontextprotocol/server-memory")
  846. # Remote HTTP server
  847. api = load("https://api.example.com/mcp")
  848. # Remote server with authentication
  849. secure_api = load(
  850. "https://api.example.com/mcp",
  851. headers={"Authorization": "Bearer YOUR_TOKEN"}
  852. )
  853. # Inspect what's available
  854. print(weather.tools) # List of tool schemas
  855. print(weather.get_alerts) # Callable function
  856. result = weather.get_alerts(state="CA")
  857. ```
  858. Clean, simple, {python}ic. That’s the goal. 🎯
  859. ------------------------------------------------------------------------
  860. ## Architecture Overview
  861. ┌─────────────────────────────────────────────────────────────────┐
  862. │ Your {python} Code (MCP Client) │
  863. │ │
  864. │ from mcp2py import load │
  865. │ │
  866. │ server = load("npx weather-server") │
  867. │ result = server.get_forecast(lat=37.7, lon=-122.4) │
  868. │ │
  869. │ ┌──────────────────────────────────────────────────────┐ │
  870. │ │ Optional: Use with AI SDKs │ │
  871. │ │ │ │
  872. │ │ import dspy │ │
  873. │ │ agent = dspy.ReAct( │ │
  874. │ │ Signature, │ │
  875. │ │ tools=server.tools # ← mcp2py │ │
  876. │ │ ) │ │
  877. │ └──────────────────────────────────────────────────────┘ │
  878. └─────────────────────────────────────────────────────────────────┘
  879. ↕ JSON-RPC over stdio
  880. ┌─────────────────────────────────────────────────────────────────┐
  881. │ MCP Server Process (separate process) │
  882. │ │
  883. │ Node.js / {python} / Rust / whatever │
  884. │ Exposes: tools, resources, prompts │
  885. │ May request: sampling, elicitation, roots │
  886. └─────────────────────────────────────────────────────────────────┘
  887. **Key Points:** 1. **mcp2py is the client** - it speaks JSON-RPC to the
  888. server 2. **Server is a separate process** - started via `command`
  889. parameter 3. **Low-level and generic** - works with any AI SDK or
  890. standalone 4. **Bidirectional** - client calls server tools, server can
  891. request client capabilities
  892. ------------------------------------------------------------------------
  893. ## Advanced Tutorial: Composing MCP Servers with DSPy
  894. This tutorial demonstrates the full power of mcp2py by showing how
  895. to: 1. Use Notion MCP in a DSPy agent 2. Wrap that agent as its own MCP
  896. server 3. Use that server in another DSPy program
  897. This showcases true **composability** - building complex AI systems by
  898. chaining MCP servers together.
  899. ### Step 1: DSPy Agent with Notion MCP
  900. First, let’s create a DSPy agent that can search and organize
  901. information in Notion:
  902. ``` python
  903. import dspy
  904. from mcp2py import load
  905. # Configure DSPy with your LLM
  906. dspy.configure(lm=dspy.LM("openai/gpt-4.1"))
  907. # Load Notion MCP server
  908. notion = load("https://mcp.notion.com/mcp", auth="oauth")
  909. # Define a DSPy signature for a research assistant
  910. class NotionResearcher(dspy.Signature):
  911. """Research assistant that searches Notion workspace."""
  912. query: str = dspy.InputField(desc="Research query")
  913. summary: str = dspy.OutputField(desc="Summary of findings")
  914. # Create DSPy agent with Notion tools
  915. researcher = dspy.ReAct(NotionResearcher, tools=notion.tools)
  916. # Test the agent
  917. result = researcher(query="What are our Q1 2025 goals?")
  918. print(result.summary)
  919. ```
  920. [11/03/25 07:20:44] INFO OAuth authorization URL: oauth.py:340
  921. https://mcp.notion.com/authorizresponse_typ...
  922. INFO 🎧 OAuth callback server started on http://localhost:40621 oauth.py:358
  923. AI response > No information was found regarding our Q1 2025 goals due to repeated execution errors when attempting to search or create documentation in Notion. All attempts to gather relevant data or create a new page were unsuccessful.
  924. ### Step 2: Wrap the Agent as an MCP Server
  925. Now let’s turn this Notion-powered agent into its own MCP server using
  926. FastMCP:
  927. ``` python
  928. # notion_research_server.py
  929. from fastmcp import FastMCP
  930. from mcp2py import load
  931. import dspy
  932. # Initialize FastMCP
  933. mcp = FastMCP("Notion Research Server")
  934. # Load Notion and configure DSPy
  935. notion = load("https://mcp.notion.com/mcp", auth="oauth")
  936. dspy.configure(lm=dspy.LM("openai/gpt-4.1"))
  937. class NotionResearcher(dspy.Signature):
  938. """Research assistant that searches Notion workspace."""
  939. query: str = dspy.InputField(desc="Research query")
  940. summary: str = dspy.OutputField(desc="Summary of findings")
  941. researcher = dspy.ReAct(NotionResearcher, tools=notion.tools)
  942. @mcp.tool()
  943. def research_notion(query: str) -> str:
  944. """Research a topic by searching the Notion workspace.
  945. Args:
  946. query: The research question or topic to investigate
  947. Returns:
  948. A comprehensive summary of findings from Notion
  949. """
  950. result = researcher(query=query)
  951. return result.summary
  952. # Run the server
  953. if __name__ == "__main__":
  954. mcp.run()
  955. ```
  956. Save this as `notion_research_server.py` and you now have a custom MCP
  957. server!
  958. ### Step 3: Use the Custom Server in Another DSPy Program
  959. Finally, let’s use our custom Notion Research Server in a higher-level
  960. DSPy agent:
  961. ``` python
  962. import dspy
  963. from mcp2py import load
  964. # Configure DSPy
  965. dspy.configure(lm=dspy.LM("openai/gpt-4.1"))
  966. # Load our custom Notion Research Server
  967. research_server = load("uv run notion_research_server.py")
  968. # Create a high-level report writer
  969. class ReportWriter(dspy.Signature):
  970. """Executive assistant that creates comprehensive reports."""
  971. topic: str = dspy.InputField(desc="Report topic")
  972. sections: str = dspy.InputField(desc="Comma-separated section topics")
  973. report: str = dspy.OutputField(desc="Comprehensive markdown report")
  974. # Create agent with our research server tools
  975. report_writer = dspy.ReAct(ReportWriter, tools=research_server.tools)
  976. # Generate a comprehensive report
  977. result = report_writer(
  978. topic="Company Strategy Review",
  979. sections="Q1 Goals, Recent Achievements, Upcoming Initiatives, Team Updates"
  980. )
  981. print("="*60)
  982. print(result.report)
  983. print("="*60)
  984. ```
  985. ============================================================
  986. # Company Strategy Review
  987. ## Q1 Goals
  988. *Unable to retrieve specific information due to access issues.*
  989. ## Recent Achievements
  990. *Unable to retrieve specific information due to access issues.*
  991. ## Upcoming Initiatives
  992. *Unable to retrieve specific information due to access issues.*
  993. ## Team Updates
  994. *Unable to retrieve specific information due to access issues.*
  995. ---
  996. *Note: This report could not be completed with current data access. Please provide the necessary information or resolve access issues to enable a comprehensive review.*
  997. ============================================================
  998. ### What Just Happened?
  999. This example demonstrates **three levels of composition**:
  1000. 1. **Level 1**: Notion MCP provides raw tools (search, fetch, create)
  1001. 2. **Level 2**: DSPy agent + Notion MCP = Research Assistant (wrapped
  1002. as MCP server)
  1003. 3. **Level 3**: Another DSPy agent uses the Research Assistant to
  1004. create comprehensive reports
  1005. ### Key Benefits
  1006. - **Modularity**: Each layer is independent and reusable
  1007. - **Abstraction**: Higher levels don’t need to know about Notion’s API
  1008. - **Composability**: Mix and match different MCP servers and agents
  1009. - **Type Safety**: Full type hints and IDE support throughout the chain
  1010. - **Testability**: Each layer can be tested independently
  1011. ### Real-World Applications
  1012. This pattern enables powerful workflows:
  1013. - **Multi-Source Research**: Combine Notion, GitHub, Slack, and other
  1014. MCP servers
  1015. - **Specialized Agents**: Create domain-specific assistants (HR,
  1016. Engineering, Sales)
  1017. - **Agent Chains**: Build complex pipelines where agents call other
  1018. agents
  1019. - **API Abstraction**: Hide complexity behind simple, high-level tools
  1020. ### Next Steps
  1021. Try creating your own composed systems:
  1022. 1. Add more MCP servers (GitHub, Slack, Google Drive)
  1023. 2. Create specialized agents for different domains
  1024. 3. Build agent hierarchies with supervisors and workers
  1025. 4. Deploy as microservices for production use
  1026. The possibilities are endless when you can turn any MCP server into
  1027. Python, and any Python code into an MCP server!

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.