Metadata-Version: 2.5
Name: mcpico
Version: 0.1.1
Summary: A lightweight, fully typed Python SDK for the Model Context Protocol
Project-URL: Repository, https://github.com/nolantw/mcpico
Author-email: Nolan <300344883+nolantw@users.noreply.github.com>
License-Expression: MIT
License-File: LICENSE
Keywords: asyncio,json-rpc,llm,mcp,model-context-protocol
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: jsonschema-rs>=0.30
Requires-Dist: msgspec>=0.19
Provides-Extra: all
Requires-Dist: authlib>=1.5; extra == 'all'
Requires-Dist: granian>=2.2; extra == 'all'
Requires-Dist: httpx2>=2.16; extra == 'all'
Requires-Dist: joserfc>=1.0; extra == 'all'
Requires-Dist: sse-starlette>=2.2; extra == 'all'
Requires-Dist: starlette>=0.46; extra == 'all'
Provides-Extra: auth
Requires-Dist: authlib>=1.5; extra == 'auth'
Requires-Dist: granian>=2.2; extra == 'auth'
Requires-Dist: httpx2>=2.16; extra == 'auth'
Requires-Dist: joserfc>=1.0; extra == 'auth'
Requires-Dist: sse-starlette>=2.2; extra == 'auth'
Requires-Dist: starlette>=0.46; extra == 'auth'
Provides-Extra: http
Requires-Dist: granian>=2.2; extra == 'http'
Requires-Dist: httpx2>=2.16; extra == 'http'
Requires-Dist: sse-starlette>=2.2; extra == 'http'
Requires-Dist: starlette>=0.46; extra == 'http'
Description-Content-Type: text/markdown

<p align="center">
  <img src="https://raw.githubusercontent.com/nolantw/mcpico/main/docs/public/icon.svg" width="88" height="88" alt="">
</p>

<h1 align="center">MCPico</h1>

<p align="center">
  <strong>MCP, made simple.</strong>
</p>

<p align="center">
  <a href="#install">Install</a>&nbsp;&nbsp;&nbsp;
  <a href="https://github.com/nolantw/mcpico/tree/main/docs">Documentation</a>
</p>

---

A small, fully typed Python SDK for the [Model Context Protocol](https://modelcontextprotocol.io):
client and server, over stdio and Streamable HTTP, with OAuth 2.1. It speaks protocol revision
**2026-07-28**, and **2025-11-25** for older peers.

```python
from mcpico import Server

server = Server("demo")


@server.tool
def add(a: int, b: int = 0) -> int:
    """Add two numbers."""
    return a + b


server.run()  # stdio; server.run("http", port=8000) for Streamable HTTP
```

Input and output schemas come from type hints, docstrings become descriptions, and arguments are
validated before your function runs.

## Install

```console
pip install mcpico            # core and stdio
pip install "mcpico[http]"    # Streamable HTTP (client and server)
pip install "mcpico[auth]"    # OAuth 2.1
```

With uv:

```console
uv add mcpico
uv add "mcpico[http]"
uv add "mcpico[auth]"
```

Python 3.12 or newer.

## Servers

### Tools

```python
from typing import Annotated

import msgspec

from mcpico import Context, Server

server = Server("weather", "1.0", instructions="Forecasts for European cities.")


class Forecast(msgspec.Struct):
    city: str
    celsius: float


@server.tool
async def forecast(
    city: Annotated[str, msgspec.Meta(description="City name")], ctx: Context
) -> Forecast:
    """Tomorrow's forecast."""
    await ctx.report_progress(1, 2, "fetching")
    return Forecast(city, 21.5)
```

- Parameters annotated with `Context` are injected rather than exposed to clients.
- Functions returning `str`, content blocks or `None` produce plain content. Anything else is
  structured content, with an output schema derived from the return type.
- Exceptions become tool errors (`isError: true`) that the model can see.
- Pass `input_schema=` or `output_schema=` to use hand-written JSON Schemas instead.

### Resources and prompts

```python
@server.resource("file:///readme.txt", mime_type="text/plain")
def readme() -> str:
    return "Hello"


@server.resource("users://{user_id}/avatar", mime_type="image/png")
def avatar(user_id: int) -> bytes:  # bytes are sent as a blob
    ...


@server.prompt
def review(code: str, language: str = "python") -> str:
    """Review some code."""
    return f"Please review this {language} code:\n\n{code}"
```

URIs containing `{variable}` (one path segment) or `{+variable}` (any text) register templates.

### Asking the user

A tool, resource or prompt can ask the client for input. The server holds no session for this:
it returns the question, and the client retries the request with the answer. The handler then
runs again from the start, and `elicit` calls that were already answered return their answers.

```python
class Confirm(msgspec.Struct):
    confirm: bool


@server.tool
def delete_project(name: str, ctx: Context) -> str:
    answer = ctx.elicit(f"Really delete {name}?", Confirm)
    if answer is None or not answer.confirm:  # None: declined or cancelled
        return "Kept."
    ...
    return "Deleted."
```

The form is derived from the struct or dataclass, whose fields must be strings, numbers,
booleans or enums (`X | None` makes a field optional). Pass a JSON Schema instead to get the raw
`ElicitResult`. Code before an `elicit` call can run more than once, so keep side effects after the last one.
`ctx.elicit_url(...)` sends the user to a URL instead. The state carried between rounds is signed,
bound to the request and the caller, and expires. Pass `state_secret=` to `Server` when several
processes serve the same clients.

### Protocol versions

A server answers 2026-07-28 and 2025-11-25 clients on the same endpoint, from the same tools,
resources and prompts. Requests carrying 2026-07-28 metadata are served statelessly; an
`initialize` request opens a 2025-11-25 session (one per stdio process, or per `Mcp-Session-Id`
over HTTP), in which `elicit` becomes an `elicitation/create` request to the client.
`ctx.protocol_version` tells a handler which revision is in use. To serve only some revisions:

```python
from mcpico.types import LATEST_PROTOCOL_VERSION

server = Server("demo", protocol_versions=[LATEST_PROTOCOL_VERSION])
```

### Change notifications

```python
server.add_tool(some_function)  # clients listening for tool changes are told
server.notify_resource_updated("file:///readme.txt")
```

### Running

```python
server.run()  # stdio
server.run("http", host="127.0.0.1", port=8000)  # Streamable HTTP, on Granian
```

Inside an existing event loop, use `await server.serve(...)` and cancel the task to stop. The HTTP
server shuts down gracefully: it ends open subscription streams and finishes in-flight requests.
`mcpico.http.serve_async` also takes `ready=` (an `asyncio.Event` set once the server accepts
connections) and `ssl_cert`/`ssl_key` for HTTPS.

For other deployments, `create_app` returns a standard ASGI application:

```python
from mcpico.http import create_app

app = create_app(server, allowed_origins=["https://app.example.com"])
```

```console
granian --interface asgi --workers 4 myserver:app
```

Requests are independent, so workers share nothing but a common `state_secret`. Change
notifications reach only subscribers connected to the same process. 2025-11-25 sessions live in
the process that opened them: route them by `Mcp-Session-Id`, or serve only 2026-07-28.
Browser requests from origins other than localhost are rejected unless listed in
`allowed_origins`.

## Clients

```python
import asyncio

from mcpico import Client, StdioTransport


async def main() -> None:
    async with Client(StdioTransport("python", ["server.py"])) as client:
        tools = await client.list_tools()
        result = await client.call_tool("add", {"a": 1, "b": 2})
        print(result.parse(int))


asyncio.run(main())
```

### Transports

`StdioTransport` starts the server as a subprocess; the command and arguments may be paths.
Over Streamable HTTP:

```python
from mcpico.http import HttpTransport

client = Client(HttpTransport("https://mcp.example.com/mcp"))
```

### Results

```python
result = await client.call_tool("weather", {"city": "Oslo"})
weather = result.parse(Weather)  # structured content; raises ToolError if the tool failed
print(result.text)  # the text blocks, joined

note = await client.read_resource("notes://todo")
print(note.text)  # or note.data for binary contents
```

Structured content is checked against the tool's output schema, and `list_*` methods follow
pagination.

### Questions, progress and timeouts

```python
from mcpico.types import ElicitRequest, ElicitResult


async def ask(request: ElicitRequest) -> ElicitResult:
    print(request.message)
    return ElicitResult(action="accept", content={"confirm": True})


async with Client(transport, elicitation=ask) as client:
    await client.call_tool("delete_project", {"name": "old"}, timeout=30, progress=print)
```

A timeout or a cancelled task also cancels the request on the server.

### Change notifications

```python
async with client.listen(tools=True) as subscription:
    async for notification in subscription:
        print(notification.method)
```

### Protocol versions

The client speaks 2026-07-28 first. When a server does not understand it, the client falls back
to a 2025-11-25 `initialize` session, with the same API.

- `Client(..., protocol_versions=[...])` restricts the versions it may use.
- A custom transport implements `SessionTransport` to support the fallback.

## Authorization

A server checks bearer tokens and publishes its Protected Resource Metadata:

```python
from mcpico.auth import ProtectedResource

auth = ProtectedResource.jwt(
    "https://mcp.example.com/mcp",
    issuer="https://auth.example.com",
    jwks_uri="https://auth.example.com/.well-known/jwks.json",
    required_scopes=("mcp",),
)
server.run("http", host="0.0.0.0", port=8000, auth=auth)
```

Handlers read the validated token from `ctx.access_token`, and can raise
`InsufficientScopeError(["admin"])` to ask the client to step up. Implement `TokenVerifier` to
validate tokens some other way, such as introspection, and pass it to `ProtectedResource(...)`.

A client uses `OAuth`, an `httpx2.Auth`. It discovers the authorization server, runs the
authorization code flow with PKCE, and refreshes tokens:

```python
from mcpico.auth.client import ClientCredentials, LoopbackBrowser, OAuth

browser = LoopbackBrowser(8765)  # opens the system browser, listens for the redirect
oauth = OAuth(
    authorize=browser,
    redirect_uri=browser.redirect_uri,
    credentials={"https://auth.example.com": ClientCredentials("my-client-id")},
)
client = Client(HttpTransport("https://mcp.example.com/mcp", auth=oauth))
```

`authorize` can be any async function that sends the user to a URL and returns the URL they were
redirected to. Without it, the client credentials grant is used. Instead of pre-registered credentials,
`client_metadata_url=` identifies the client with a Client ID Metadata Document.

## Scope

MCPico implements the current protocol revision, and revision 2025-11-25 for clients and servers
that do not speak it yet. Features the specification deprecates or removed are not provided in
either: roots, sampling, logging and dynamic client registration. With 2025-11-25 peers,
`Client.listen` is unavailable and HTTP sessions are not resumable.

## Development

```console
uv sync --all-extras
uv run ruff format --check .
uv run ruff check .
uv run pyright
uv run mypy
uv run pyrefly check
uv run ty check  # advisory
uv run pytest
```

The documentation site, with an API reference generated from the docstrings, is in
[`docs/`](https://github.com/nolantw/mcpico/tree/main/docs).

## License

MIT
