Skip to content
Back to search

zeromcp

Zero-dependency MCP server implementation.

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/mrexodia--zeromcp/badge.svg)](/listings/mrexodia--zeromcp)

HTML

<a href="/listings/mrexodia--zeromcp"><img src="/api/listings/mrexodia--zeromcp/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.

pip install zeromcp

Or with uv:

uv add zeromcp

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 · 415 lines

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

  1. # zeromcp
  2. **Minimal MCP server implementation in pure Python.**
  3. A lightweight, handcrafted implementation of the [Model Context Protocol](https://modelcontextprotocol.io/) focused on what most users actually need: exposing tools with clean Python type annotations.
  4. ## Features
  5. - ✨ **Zero dependencies** - Pure Python, standard library only
  6. - 🎯 **Type-safe** - Native Python type annotations for everything
  7. - 🚀 **Fast** - Minimal overhead, maximum performance
  8. - 🛠️ **Handcrafted** - Written by a human<sup>[1](#ai-usage)</sup>, verified against the spec
  9. - 🌐 **HTTP/SSE transport** - Streamable responses
  10. - 📡 **Stdio transport** - For legacy clients
  11. - 📦 **Tiny** - Compact codebase with no framework dependency
  12. ## Installation
  13. ```bash
  14. pip install zeromcp
  15. ```
  16. Or with uv:
  17. ```bash
  18. uv add zeromcp
  19. ```
  20. ## Quick Start
  21. ```python
  22. from typing import Annotated
  23. from zeromcp import McpServer
  24. mcp = McpServer("my-server")
  25. @mcp.tool
  26. def greet(
  27. name: Annotated[str, "Name to greet"],
  28. age: Annotated[int | None, "Age of person"] = None
  29. ) -> str:
  30. """Generate a greeting message"""
  31. if age:
  32. return f"Hello, {name}! You are {age} years old."
  33. return f"Hello, {name}!"
  34. if __name__ == "__main__":
  35. mcp.serve("127.0.0.1", 8000)
  36. ```
  37. The optional MCP `instructions` field tells clients how the server and its features should be used. Clients may add these instructions to the model's system prompt:
  38. ```python
  39. mcp = McpServer(
  40. "my-server",
  41. instructions="Use the greet tool when the user asks to greet someone.",
  42. )
  43. ```
  44. Then manually test your MCP server with the [inspector](https://github.com/modelcontextprotocol/inspector):
  45. ```bash
  46. npx -y @modelcontextprotocol/inspector
  47. ```
  48. Once things are working you can configure the `mcp.json`:
  49. ```json
  50. {
  51. "mcpServers": {
  52. "my-server": {
  53. "type": "http",
  54. "url": "http://127.0.0.1:8000/mcp"
  55. }
  56. }
  57. }
  58. ```
  59. ## Stdio Transport
  60. For MCP clients that only support stdio transport:
  61. ```python
  62. from zeromcp import McpServer
  63. mcp = McpServer("my-server")
  64. @mcp.tool
  65. def greet(name: str) -> str:
  66. """Generate a greeting"""
  67. return f"Hello, {name}!"
  68. if __name__ == "__main__":
  69. mcp.stdio()
  70. ```
  71. Then configure in `mcp.json` (different for every client):
  72. ```json
  73. {
  74. "mcpServers": {
  75. "my-server": {
  76. "command": "python",
  77. "args": ["path/to/server.py"]
  78. }
  79. }
  80. }
  81. ```
  82. ## Type Annotations
  83. zeromcp uses native Python `Annotated` types for schema generation:
  84. ```python
  85. from typing import Annotated, Optional, TypedDict, NotRequired
  86. class GreetingResponse(TypedDict):
  87. message: Annotated[str, "Greeting message"]
  88. name: Annotated[str, "Name that was greeted"]
  89. age: Annotated[NotRequired[int], "Age if provided"]
  90. @mcp.tool
  91. def greet(
  92. name: Annotated[str, "Name to greet"],
  93. age: Annotated[Optional[int], "Age of person"] = None
  94. ) -> GreetingResponse:
  95. """Generate a greeting message"""
  96. if age is not None:
  97. return {
  98. "message": f"Hello, {name}! You are {age} years old.",
  99. "name": name,
  100. "age": age
  101. }
  102. return {
  103. "message": f"Hello, {name}!",
  104. "name": name
  105. }
  106. ```
  107. ## Union Types
  108. Tools can accept multiple input types:
  109. ```python
  110. from typing import Annotated, TypedDict
  111. class StructInfo(TypedDict):
  112. name: Annotated[str, "Structure name"]
  113. size: Annotated[int, "Structure size in bytes"]
  114. fields: Annotated[list[str], "List of field names"]
  115. @mcp.tool
  116. def struct_get(
  117. names: Annotated[list[str], "Array of structure names"]
  118. | Annotated[str, "Single structure name"]
  119. ) -> list[StructInfo]:
  120. """Retrieve structure information by names"""
  121. return [
  122. {
  123. "name": name,
  124. "size": 128,
  125. "fields": ["field1", "field2", "field3"]
  126. }
  127. for name in (names if isinstance(names, list) else [names])
  128. ]
  129. ```
  130. ## Error Handling
  131. ```python
  132. from zeromcp import McpToolError
  133. @mcp.tool
  134. def divide(
  135. numerator: Annotated[float, "Numerator"],
  136. denominator: Annotated[float, "Denominator"]
  137. ) -> float:
  138. """Divide two numbers"""
  139. if denominator == 0:
  140. raise McpToolError("Division by zero")
  141. return numerator / denominator
  142. ```
  143. ## Resources
  144. Expose read-only data via URI patterns. Resources are serialized as JSON.
  145. ```python
  146. from typing import Annotated
  147. @mcp.resource("file://data.txt")
  148. def read_file() -> dict:
  149. """Get information about data.txt"""
  150. return {"name": "data.txt", "size": 1024}
  151. @mcp.resource("file://{filename}")
  152. def read_any_file(
  153. filename: Annotated[str, "Name of file to read"]
  154. ) -> dict:
  155. """Get information about any file"""
  156. return {"name": filename, "size": 2048}
  157. ```
  158. ## Prompts
  159. Expose reusable prompt templates with typed arguments.
  160. ```python
  161. from typing import Annotated
  162. @mcp.prompt
  163. def code_review(
  164. code: Annotated[str, "Code to review"],
  165. language: Annotated[str, "Programming language"] = "python"
  166. ) -> str:
  167. """Review code for bugs and improvements"""
  168. return f"Please review this {language} code:\n\n```{language}\n{code}\n```"
  169. ```
  170. ## Tool annotations
  171. MCP 2025-03-26+ supports tool behavior hints:
  172. ```python
  173. @mcp.tool(title="Get System Status", read_only=True, destructive=False, idempotent=True, open_world=False)
  174. def get_status() -> dict:
  175. """Read current system status"""
  176. return {"ok": True}
  177. ```
  178. ## Request context
  179. Tools, resources, and prompts can inspect the current MCP request context:
  180. ```python
  181. @mcp.tool
  182. def inspect_request() -> dict:
  183. return {
  184. "request_id": mcp.context.request_id,
  185. "meta": mcp.context.meta,
  186. "auth_subject": mcp.context.auth.subject if mcp.context.auth else None,
  187. }
  188. ```
  189. `mcp.context.meta` contains the request `_meta` object, including fields such as `progressToken`.
  190. ## Logging notifications (stdio)
  191. Stdio servers can send MCP `notifications/message` logging notifications while
  192. the transport is running:
  193. ```python
  194. @mcp.tool
  195. def rebuild_index() -> str:
  196. mcp.send_log_message("info", "Rebuilding the index", logger="search")
  197. # ...
  198. mcp.send_log_message("notice", {"indexed": 42}, logger="search")
  199. return "done"
  200. ```
  201. The stdio server advertises the MCP `logging` capability and handles
  202. `logging/setLevel`. Messages below the client-selected level are omitted; the
  203. default level is `info`. Supported levels are `debug`, `info`, `notice`,
  204. `warning`, `error`, `critical`, `alert`, and `emergency`.
  205. `send_log_message` is safe to call from concurrent handlers or background
  206. threads, but raises `RuntimeError` when no stdio transport is active. Streamable
  207. HTTP logging notifications are not currently supported.
  208. ## Async tools
  209. Async tools, resources, prompts, and JSON-RPC methods are supported. HTTP and stdio transports stay synchronous by default; async stdio concurrency is opt-in with `await mcp.stdio_async()`.
  210. ```python
  211. import asyncio
  212. @mcp.tool
  213. async def slow_lookup(key: str) -> str:
  214. await asyncio.sleep(1)
  215. return key
  216. ```
  217. ## Cancellation
  218. Cancellation is supported for async tools, resources, and prompts. ZeroMCP
  219. runs each async request as an `asyncio.Task`; `notifications/cancelled` calls
  220. `Task.cancel(reason)`, so the handler receives `asyncio.CancelledError` at its
  221. next await point. A cancelled call produces no JSON-RPC response, even if the
  222. handler suppresses the exception and returns a value.
  223. ```python
  224. @mcp.tool
  225. async def remote_operation() -> str:
  226. operation = asyncio.create_task(start_remote_operation())
  227. try:
  228. return await asyncio.shield(operation)
  229. except asyncio.CancelledError:
  230. await cancel_remote_operation()
  231. try:
  232. await asyncio.shield(operation) # wait for safe remote unwinding
  233. except Exception:
  234. pass
  235. raise
  236. ```
  237. Synchronous handlers are not cancellable. Cancelling an asyncio task cannot
  238. stop a running Python thread or native function safely, so ZeroMCP ignores
  239. cancellation notifications for synchronous handlers rather than pretending to
  240. terminate them. Cancellation follows the callable registered with ZeroMCP: a
  241. synchronous decorator makes a handler synchronous even if it returns a
  242. coroutine. Use an `async def` wrapper to preserve cancellation support.
  243. The transport must also be able to receive the cancellation notification while
  244. the original request is running. Use `await mcp.stdio_async()` for stdio;
  245. `mcp.stdio()` processes one message at a time and therefore cannot receive a
  246. cancellation until after the active request returns. Streamable HTTP and SSE
  247. can receive cancellation concurrently for async handlers.
  248. Cancellations are matched per transport session. Over Streamable HTTP the cancellation notification arrives as a separate POST, so the client must echo the `Mcp-Session-Id` header from `initialize` (the spec requires clients to do this). Requests from clients that omit the header cannot be correlated — JSON-RPC ids are only unique within a session, so matching bare ids would let one client cancel another's request — and such cancellations are ignored, which the spec permits.
  249. ## HTTP sessions
  250. zeromcp assigns an `Mcp-Session-Id` on every successful Streamable HTTP `initialize` and remembers the negotiated protocol version for that session. By default the session id is advisory; set `mcp.require_streamable_http_session = True` to reject non-initialize requests without a valid session (400/404 per spec).
  251. Clients can terminate a session with `DELETE /mcp` and the `Mcp-Session-Id` header. Session state is also bounded by `mcp.max_http_sessions` (default 1024) with least-recently-used eviction; requests with an evicted session id receive 404, and per the spec the client then starts a new session with a fresh `initialize`. With OAuth configured, unauthenticated requests are rejected before any session is created.
  252. ## OAuth resource server
  253. zeromcp can act as an MCP OAuth resource server. Token validation is provided by your application:
  254. ```python
  255. from zeromcp import McpAuthInfo
  256. @mcp.oauth(
  257. resource="https://mcp.example.com/mcp",
  258. authorization_servers=["https://auth.example.com"],
  259. scopes_supported=["mcp"],
  260. required_scopes=["mcp"],
  261. )
  262. def verify_token(token: str, resource: str) -> McpAuthInfo | None:
  263. if token == "expected":
  264. return McpAuthInfo(
  265. subject="user-123",
  266. scopes=frozenset({"mcp"}),
  267. claims={"sub": "user-123"},
  268. )
  269. return None
  270. ```
  271. When OAuth is configured, HTTP MCP requests require `Authorization: Bearer <token>`. zeromcp exposes OAuth Protected Resource Metadata at `/.well-known/oauth-protected-resource`.
  272. When no `resource_metadata_url` is given, the metadata URL advertised in `WWW-Authenticate` is inferred from the request's `Host` header. This works out of the box for direct connections, but behind a reverse proxy you should set `resource_metadata_url` (and `resource`) explicitly so the advertised URLs match your public address.
  273. The example server includes a static-token OAuth verifier for local testing:
  274. ```bash
  275. uv run examples/mcp_example.py --transport http://127.0.0.1:5001 --oauth --oauth-token dev-token --oauth-resource http://127.0.0.1:5001/mcp
  276. ```
  277. It can also validate HS256 JWTs (`sub`, `scope`, `exp`, `nbf`, and `aud` claims) using only the standard library — see `verify_jwt_hs256` in `examples/mcp_example.py`:
  278. ```bash
  279. uv run examples/mcp_example.py --transport http://127.0.0.1:5001 --oauth --oauth-jwt-secret my-secret --oauth-resource http://127.0.0.1:5001/mcp
  280. ```
  281. ## CORS
  282. By default, zeromcp allows CORS requests from localhost origins (`localhost`, `127.0.0.1`, `::1`) on **any port**. This allows tools like the MCP Inspector or local AI tools to communicate with your MCP server.
  283. ```python
  284. from zeromcp import McpServer
  285. mcp = McpServer("my-server")
  286. # Default: allow localhost on any port
  287. mcp.cors_allowed_origins = mcp.cors_localhost
  288. # Allow all origins (use with caution)
  289. mcp.cors_allowed_origins = "*"
  290. # Allow specific origins
  291. mcp.cors_allowed_origins = [
  292. "http://localhost:3000",
  293. "https://myapp.example.com",
  294. ]
  295. # Disable CORS (blocks all browser cross-origin requests)
  296. mcp.cors_allowed_origins = None
  297. # Custom logic
  298. mcp.cors_allowed_origins = lambda origin: origin.endswith(".example.com")
  299. ```
  300. Note: CORS only affects browser-based requests. Non-browser clients like `curl` or MCP desktop apps are unaffected by this setting.
  301. ## Supported clients
  302. The following clients have been tested:
  303. - [Claude Code](https://code.claude.com/docs/en/mcp#installing-mcp-servers)
  304. - [Claude Desktop](https://modelcontextprotocol.io/docs/develop/connect-local-servers#installing-the-filesystem-server) (_stdio only_)
  305. - [Visual Studio Code](https://code.visualstudio.com/docs/copilot/customization/mcp-servers)
  306. - [Roo Code](https://docs.roocode.com/features/mcp/using-mcp-in-roo) / [Cline](https://docs.cline.bot/mcp/configuring-mcp-servers) / [Kilo Code](https://kilocode.ai/docs/features/mcp/using-mcp-in-kilo-code)
  307. - [LM Studio](https://lmstudio.ai/docs/app/mcp)
  308. - [Jan](https://www.jan.ai/docs/desktop/mcp#configure-and-use-mcps-within-jan)
  309. - [Gemini CLI](https://geminicli.com/docs/tools/mcp-server/#how-to-set-up-your-mcp-server)
  310. - [Cursor](https://cursor.com/docs/context/mcp)
  311. - [Windsurf](https://docs.windsurf.com/windsurf/cascade/mcp)
  312. - [Zed](https://zed.dev/docs/ai/mcp) (_stdio only_)
  313. - [Warp](https://docs.warp.dev/knowledge-and-collaboration/mcp#adding-an-mcp-server)
  314. _Note_: generally the `/mcp` endpoint is preferred, but not all clients support it correctly.
  315. <a name="ai-usage"></a>
  316. <sup>1</sup>README and some of the tests written by Claude

Ratings and comments

Sign in to rate this skill.

Sign in

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