---
title: core
description: Serve Python functions as MCP tools, and call MCP servers
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

Serve Python functions as MCP tools, or call another MCP server from Python.

## Serving tools

Pass sync or async functions to [`MCPServer`](core.md#mcpserver). Fastcore's `get_schema` reads their docments to produce tool descriptions and `inputSchema`. No separate registration code is needed.

The server dispatches message dictionaries without keeping a client session. Its stdio transport handles concurrent calls and nested requests. A tool can await [`MCPServer.elicit`](core.md#mcpserver.elicit) to ask for structured user input while its call remains active. For HTTP, [`create_app`](core.md#create_app) supplies a mountable ASGI app with one POST endpoint; [`serve_mcp`](core.md#serve_mcp) runs it under uvicorn.

## Auth

[`auth_app`](core.md#auth_app) checks a static bearer token with a constant-time comparison. It is ASGI middleware, not an OAuth implementation. Treat access to your tools as permission to run their Python code. [`serve_mcp`](core.md#serve_mcp) refuses a non-loopback bind without `token=` or `$MCPMINI_TOKEN`. Use `no_token=True` only when you provide protection elsewhere, such as a VPN or authenticating proxy.

## The command

`mcpmini tools.py` serves a file's docmented functions over stdio. This is the command an MCP host can launch. Add `--transport http` and the deployment flags for HTTP. From Python, [`load_server`](core.md#load_server) performs the same file-to-server conversion. The file's docstring supplies the server instructions.

## Calling servers

Use `MCPClient.stdio(argv)` or `MCPClient.http(url)` as an async context manager. The client initializes the connection and binds `tools/list` entries as Python callables. Fastcore's `mk_tool` reconstructs their signatures, documentation, and defaults from the schemas.

Bound tools return text and raise on `isError`. Use `call_tool` for the raw result, including non-text blocks. A stdio client's `on_request(method, params)` can answer nested requests such as elicitation. The HTTP client accepts JSON or SSE replies and returns a server-issued `Mcp-Session-Id` on later POSTs. Its `delete` method requests session termination when you no longer need a server-side session.

The tests below pair each side with the official SDK. These cover the supported tool workflow, not every MCP feature or server.

This implementation negotiates the `2025-11-25`, `2025-06-18`, and `2025-03-26` protocol versions. They use an `initialize` handshake before ordinary JSON-RPC calls.

The [2026-07-28 revision](https://blog.modelcontextprotocol.io/posts/2026-07-28/) removes that handshake and session header in favor of self-describing requests. Keeping connection handling outside `dispatch` makes that change easier to accommodate, but this code does not yet implement the new revision.

```python
from fastcore.test import *
import shutil, socket, tempfile
```

## Messages

[`jreq`](core.md#jreq) builds a JSON-RPC request when you pass an id, or a notification without one. [`jtool`](core.md#jtool) builds a `tools/call` request and supplies an empty `arguments` object when no arguments are given.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L56)

### jtool

```python
def jtool(
    name, id:int=1, **arguments
):
```

*A `tools/call` request; omitted arguments become an empty object.*

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L49)

### jreq

```python
def jreq(
    method, id=None, **params
):
```

*JSON-RPC request, or notification when `id` is None.*

Use [`jresp`](core.md#jresp) for a result and [`jerr`](core.md#jerr) for a JSON-RPC error reply.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L62)

### jerr

```python
def jerr(
    id, code, message
):
```

*JSON-RPC error reply; MCP uses -32601 for unknown methods, -32602 for bad params, -32603 for handler failures*

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L61)

### jresp

```python
def jresp(
    id, result
):
```

Stdio carries one JSON message per line. [`send_jmsg`](core.md#send_jmsg) writes that line; [`recv_jmsg`](core.md#recv_jmsg) reads it and returns `None` at EOF.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L72)

### recv\_jmsg

```python
async def recv_jmsg(
    reader
):
```

*Read one newline-delimited JSON message; None at EOF.*

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L67)

### send\_jmsg

```python
async def send_jmsg(
    writer, msg
):
```

*Write one newline-delimited JSON message.*

## Tools from functions

A tool is just a docmented function. Its name, docstring, annotations, and parameter comments give `get_schema` the information MCP needs. Pass `pname='inputSchema'` to use MCP's name for the argument schema:

```python
def fahrenheit(
    celsius:float, # Temperature to convert
)->float:
    "Convert Celsius to Fahrenheit"
    return celsius*9/5+32

get_schema(fahrenheit, pname='inputSchema')
```

```output
{'name': 'fahrenheit',
 'description': 'Convert Celsius to Fahrenheit\n\nReturns:\n- type: number',
 'inputSchema': {'type': 'object',
  'properties': {'celsius': {'description': 'Temperature to convert',
    'type': 'number'}},
  'required': ['celsius']}}
```

MCP tool results contain a list of content blocks. [`_content`](core.md#_content) puts a string in one text block and uses `repr` for other values. This keeps Python's representation, including quotes around nested strings. A dict with a `content` key passes through unchanged, allowing tools to return images or several blocks.

```python
test_eq(_content('hi')['content'], [dict(type='text', text='hi')])
test_eq(_content(212.0)['content'][0]['text'], '212.0')
passthru = dict(content=[dict(type='image', data='AAAA', mimeType='image/png')])
test_eq(_content(passthru), passthru)
_content(dict(a=1))
```

```output
{'content': [{'type': 'text', 'text': "{'a': 1}"}], 'isError': False}
```

## The server

[`MCPServer`](core.md#mcpserver) stores its name, version, optional model instructions, and the tools' functions and schemas. Transports and tests both call `dispatch` with a message dict. The server keeps no client-session table. A context variable holds the transport callback for the current tool call.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L85)

### MCPServer

```python
def MCPServer(
    name, # Server name reported to clients
    tools:tuple=(), # Functions (sync or async) exposed as tools, described by their docments
    version:str='0.0.6', # Server version reported to clients
    instructions=None, # Optional guidance forwarded to the client's model
):
```

*An MCP tool server: `dispatch` maps one message dict to one reply dict*

`initialize` echoes a supported version or offers the newest entry in `PROTO_VERSIONS`. Unknown tool names receive JSON-RPC errors. Exceptions raised by tools instead return a traceback in `content` with `isError=True`, where the model can read and respond to the failure.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L115)

### MCPServer.dispatch

```python
async def dispatch(
    msg, requester=None
):
```

*The reply dict for one JSON-RPC message dict; None for notifications*

Our demo server converts temperatures, takes an async nap, and crashes on demand. The initialization tests request one supported version and one unsupported version:

```python
async def nap(
    ms:int=1, # How long to sleep, in milliseconds
)->str:
    "Sleep, then report back"
    await asyncio.sleep(ms/1000)
    return f'napped {ms}ms'

def crash()->str:
    "Always fails"
    return 1/0

srv = MCPServer('demo', [fahrenheit, nap, crash], instructions='Convert temperatures on request.')
init = await srv.dispatch(jreq('initialize', 1, protocolVersion='2025-06-18', capabilities={}, clientInfo=dict(name='t', version='0')))
test_eq(init['result']['protocolVersion'], '2025-06-18')
old = await srv.dispatch(jreq('initialize', 2, protocolVersion='2024-11-05'))
test_eq(old['result']['protocolVersion'], PROTO_VERSIONS[0])
init['result']
```

```output
{'protocolVersion': '2025-06-18',
 'capabilities': {'tools': {}},
 'serverInfo': {'name': 'demo', 'version': '0.0.5'},
 'instructions': 'Convert temperatures on request.'}
```

Both synchronous functions and coroutines return MCP content blocks through `tools/call`:

```python
fahrenheit_reply = await srv.dispatch(jtool('fahrenheit', celsius=100))
nap_reply = await srv.dispatch(jtool('nap', ms=2))
texts = [r['result']['content'][0]['text'] for r in (fahrenheit_reply, nap_reply)]
test_eq(texts, ['212.0','napped 2ms'])
texts
```

```output
['212.0', 'napped 2ms']
```

Calling `crash` returns its traceback as a tool result, not a JSON-RPC error:

```python
boom = (await srv.dispatch(jtool('crash')))['result']
assert boom['isError'] and 'ZeroDivisionError' in boom['content'][0]['text']
boom
```

```output
{'content': [{'type': 'text',
   'text': 'Traceback (most recent call last):\n  File "<ipython-input-11-171bf1eed883>", line 5, in _acall\n    res = f(**args)\n  File "<ipython-input-12-2bcae28d6802>", line 10, in crash\n    return 1/0\n           ~^~\nZeroDivisionError: division by zero\n'}],
 'isError': True}
```

## stdio

[`serve_stdio`](core.md#serve_stdio) reads newline-delimited JSON until EOF. A malformed JSON line receives error `-32700` with a null id, since no request id is available. Notifications receive no reply. You can supply asyncio streams or use the default stdin and stdout.

For tests, [`stdio_peer`](core.md#stdio_peer) connects the server and a small [`StdioPeer`](core.md#stdiopeer) client through a socketpair. The helper handles setup and shutdown; the messages still use the real wire format.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L160)

### stdio\_peer

```python
def stdio_peer(
    srv
):
```

*An in-process [`StdioPeer`](core.md#stdiopeer) speaking the real newline-delimited wire protocol to `srv`.*

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L138)

### StdioPeer

```python
def StdioPeer(
    reader, writer
):
```

*A small JSON-RPC peer connected to [`serve_stdio`](core.md#serve_stdio), for examples and protocol tests.*

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L184)

### serve\_stdio

```python
async def serve_stdio(
    srv, # `MCPServer` to serve
    reader=None, # asyncio stream to read messages from; stdin if None
    writer=None, # asyncio stream to write replies to; stdout if None
):
```

*Serve `srv` over newline-delimited JSON-RPC until EOF, dispatching messages concurrently*

The peer calls a tool, sends malformed JSON, then pings the server. The parse error does not prevent the ping from succeeding. Closing the peer ends the server task:

```python
async with stdio_peer(srv) as peer:
    r = await peer.call('fahrenheit', celsius=0)
    test_eq(r['result']['content'][0]['text'], '32.0')
    await peer.send_raw(b'not json\n')
    await peer.send_request('ping')
    test_eq((await peer.recv())['error']['code'], -32700)
    test_eq((await peer.recv())['result'], {})
r
```

```output
{'jsonrpc': '2.0',
 'id': 1,
 'result': {'content': [{'type': 'text', 'text': '32.0'}], 'isError': False}}
```

A tool can need more information before it can finish. Await [`MCPServer.elicit`](core.md#mcpserver.elicit) to ask the client for structured input without ending the tool call. It sends `elicitation/create` through that call's transport and returns the client's response. The tool can then continue as ordinary sequential code. Here it asks for a name before returning a greeting:

```python
async def greeting()->str:
    "Ask for a name, then greet it"
    r = await interactive.elicit('Who?', dict(type='object', properties=dict(name=dict(type='string')), required=['name']))
    return f"Hello {r['content']['name']}"

interactive = MCPServer('interactive', [greeting])
```

The client answers the nested request before it receives the greeting. A reply has no `method`; [`serve_stdio`](core.md#serve_stdio) matches its id to the pending server request:

```python
async with stdio_peer(interactive) as peer:
    await peer.send_call('greeting')
    prompt = await peer.recv()
    test_eq(prompt['method'], 'elicitation/create')
    await peer.reply(prompt, dict(action='accept', content=dict(name='Ada')))
    greeting_res = await peer.recv()
test_eq(greeting_res['result']['content'][0]['text'], 'Hello Ada')
greeting_res
```

```output
{'jsonrpc': '2.0',
 'id': 1,
 'result': {'content': [{'type': 'text', 'text': 'Hello Ada'}],
  'isError': False}}
```

The stdio loop starts a task for each request. The short nap can finish while the long nap is awaiting sleep. This also lets an interrupt tool run alongside an async execute tool on the same connection. A synchronous tool that blocks the event loop does not yield that opportunity:

```python
async with stdio_peer(srv) as peer:
    await peer.send_call('nap', ms=300)
    await peer.send_call('nap', ms=1)
    replies = [await peer.recv() for _ in range(2)]
test_eq([r['id'] for r in replies], [2, 1])
```

## Streamable HTTP

[`create_app`](core.md#create_app) exposes one POST endpoint, `/mcp` by default. It returns JSON for requests and HTTP 202 for notifications. It creates no `Mcp-Session-Id` and ignores an incoming one. GET returns 405; there is no server-push stream.

The [2025 transport specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) allows a JSON reply instead of SSE and permits 405 when a server does not offer a GET stream. Our HTTP server does not send progress notifications or nested requests.

[`auth_app`](core.md#auth_app) wraps any ASGI app. It checks the bearer token before calling that app, protecting all HTTP routes beneath it. The comparison is constant-time. This middleware handles static-token authentication, not OAuth. A deployment still needs transport security and protection against untrusted origins.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L238)

### create\_app

```python
def create_app(
    srv, # `MCPServer` to expose
    token=None, # Bearer token required on every request; open if None
    path:str='/mcp', # Endpoint path
):
```

*ASGI app serving `srv` over streamable HTTP*

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L224)

### auth\_app

```python
def auth_app(
    app, # ASGI app to guard
    token, # The bearer token every request must carry
):
```

*Wrap `app` to reject requests whose `Authorization` bearer token doesn't match `token`*

`httpx.ASGITransport` tests the app without a socket. Missing and wrong tokens get 401 before JSON parsing. The correct token permits a tool call. Authenticated GET gets 405 and a notification gets 202:

```python
app = create_app(srv, token='sesame')
async def hpost(msg, token=None, meth='POST'):
    hdrs = {'Authorization': f'Bearer {token}'} if token else {}
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url='http://t') as c:
        return await c.request(meth, '/mcp', json=msg, headers=hdrs)
ping = jreq('ping', 1)
test_eq((await hpost(ping)).status_code, 401)
test_eq((await hpost(ping, 'wrong')).status_code, 401)
test_eq((await hpost(ping)).headers['www-authenticate'], 'Bearer')
test_eq((await hpost(ping, 'sesame')).json()['result'], {})
test_eq((await hpost(ping, 'sesame', meth='GET')).status_code, 405)
test_eq((await hpost(jreq('notifications/initialized'), 'sesame')).status_code, 202)
(await hpost(jtool('fahrenheit', 2, celsius=37), 'sesame')).json()
```

```output
{'jsonrpc': '2.0',
 'id': 2,
 'result': {'content': [{'type': 'text', 'text': '98.6'}], 'isError': False}}
```

## Serving

A tool server lets its clients run your Python functions. [`serve_mcp`](core.md#serve_mcp) therefore requires a token for a non-loopback bind. Set `no_token=True` only when something else protects access, such as a VPN or fronting proxy.

This check belongs to [`serve_mcp`](core.md#serve_mcp), not [`create_app`](core.md#create_app): applications that mount the latter must arrange their own protection. Jupyter's old tokenless default is the cautionary tale here.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L254)

### serve\_mcp

```python
async def serve_mcp(
    srv, # `MCPServer` to serve
    host:str='127.0.0.1', # Interface to bind
    port:int=8000, # Port to bind
    token=None, # Bearer token; `$MCPMINI_TOKEN` if None
    no_token:bool=False, # Serve a non-loopback interface openly, when auth lives elsewhere (e.g. a VPN)
    *, path:str='/mcp', # Endpoint path
):
```

*Serve `srv` over streamable HTTP; non-loopback binds require a token unless `no_token`*

An unprotected non-loopback bind raises before opening a socket. Loopback binds may omit the token. For the client examples, however, we start a loopback server with the token `sesame`:

```python
with expect_fail(ValueError): await serve_mcp(srv, host='0.0.0.0')

def free_port():
    with socket.socket() as s:
        s.bind(('127.0.0.1', 0))
        return s.getsockname()[1]

port = free_port()
server_task = asyncio.create_task(serve_mcp(srv, port=port, token='sesame'))
url = f'http://127.0.0.1:{port}/mcp'
for _ in range(100):
    try:
        with socket.create_connection(('127.0.0.1', port), timeout=0.5): break
    except OSError: await asyncio.sleep(0.05)
url
```

```output
'http://127.0.0.1:56405/mcp'
```

## The client

Other servers can return SSE bodies or assign session ids even though ours does neither. The HTTP client accepts both JSON and SSE. After initialization, its POSTs include the negotiated `MCP-Protocol-Version` and any server-issued `Mcp-Session-Id`.

[`sse_data`](core.md#sse_data) parses a complete SSE body. Blank lines separate events; an event's `data:` lines combine into one JSON message.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L270)

### sse\_data

```python
def sse_data(
    text
):
```

*JSON messages from the `data:` lines of SSE body `text`*

```python
test_eq(sse_data('event: message\ndata: {"a": 1}\n\n: keepalive\n\ndata: {"b":\ndata:  2}\n\n'), [dict(a=1), dict(b=2)])
```

Each transport's `send` takes a message dict and returns its reply, or `None` for a notification. [`StdioTransport`](core.md#stdiotransport) starts a subprocess. While waiting for a reply, it answers server requests through the sync or async `on_request` callback. It then continues waiting for the original request id.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L279)

### StdioTransport

```python
def StdioTransport(
    argv, # Server command line, e.g. `['mymcp', '--flag']`
    env=None, # Environment for the subprocess; inherited if None
    cwd=None, # Working directory for the subprocess; inherited if None
    on_request=None, # Sync or async `(method, params)` handler for a server request received during a client request
):
```

*JSON-RPC to a subprocess over its stdin/stdout*

[`HTTPTransport`](core.md#httptransport) sends one POST per message. For SSE, it parses the response body and selects the message with the matching id.

Call `delete` when you no longer need the server-side session. It returns the HTTP response, or `None` when no session id is set. Success and 404 clear the id. A 405 response leaves it in place because the server refused termination. Other HTTP errors raise. `aclose` closes the HTTP client without requesting session termination.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L313)

### HTTPTransport

```python
def HTTPTransport(
    url, # The MCP endpoint, e.g. 'http://127.0.0.1:8000/mcp'
    token=None, # Bearer token to send with every request
    http_client=None, # An `httpx.AsyncClient` to use, e.g. over `httpx.ASGITransport`; a fresh one if None
):
```

*JSON-RPC to a streamable HTTP endpoint, one POST per message*

[`MCPClient.start`](core.md#mcpclient.start) initializes the transport, sends `notifications/initialized`, and fetches `tools/list`. `mk_tool` builds the callables in `client.tools` from those schemas, reversing the server's `get_schema` conversion.

A bound tool calls `call_text`, which joins text blocks and raises `RuntimeError` for a tool error. Use `call_tool` when you need the complete result dict. JSON-RPC errors raise in `rpc`.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L349)

### MCPClient

```python
def MCPClient(
    tr, # A transport: `StdioTransport`, `HTTPTransport`, or compatible
):
```

*Call an MCP server's tools as Python functions*

We can now call the remote converter as a Python function. Its signature and docs come from the server's schema, with parameter descriptions in `Annotated` metadata. Passing it back to `get_schema` recovers the original argument schema. The client also receives the server instructions.

The example calls the converter and uses the async tool's default argument. It then shows how a tool exception and an unknown tool name reach the Python caller:

```python
async with MCPClient.http(url, token='sesame') as c:
    test_eq(c.info['serverInfo']['name'], 'demo')
    test_eq(c.info['instructions'], 'Convert temperatures on request.')
    test_eq(list(inspect.signature(c.tools.fahrenheit).parameters), ['celsius'])
    test_eq(get_schema(c.tools.fahrenheit, pname='inputSchema')['inputSchema'], srv.specs[0]['inputSchema'])
    test_eq(await c.tools.fahrenheit(celsius=100), '212.0')
    test_eq(await c.tools.nap(), 'napped 1ms')
    with expect_fail(RuntimeError, contains='ZeroDivisionError'): await c.tools.crash()
    with expect_fail(RuntimeError, contains='-32602'): await c.call_tool('flux')
    doc_line = c.tools.fahrenheit.__doc__
doc_line
```

```output
'Convert Celsius to Fahrenheit\n\nReturns:\n- type: number'
```

Now launch a stdio server in a subprocess, as an MCP host would. The temporary script imports the exported module and defines its own converter; it cannot use this notebook's in-memory function:

```python
serverfile = Path(tempfile.mkdtemp())/'demo_stdio.py'
serverfile.write_text('''import asyncio
from mcpmini.core import MCPServer, serve_stdio

def fahrenheit(
    celsius:float, # Temperature to convert
)->float:
    "Convert Celsius to Fahrenheit"
    return celsius*9/5+32

asyncio.run(serve_stdio(MCPServer('demo-stdio', [fahrenheit])))
''')
async with MCPClient.stdio([sys.executable, str(serverfile)]) as c:
    test_eq(c.info['serverInfo']['name'], 'demo-stdio')
    res = await c.tools.fahrenheit(celsius=-40)
res
```

```output
'-40.0'
```

## Interop

Talking to ourselves is not enough to establish compatibility. First, the official SDK client initializes our HTTP server, lists its tools, and calls the converter. `streams[:2]` takes the two streams without depending on the optional session-id callback returned by older SDK versions:

```python
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client, create_mcp_http_client
```

```python
async with create_mcp_http_client(headers={'Authorization': 'Bearer sesame'}) as hc, \
        streamable_http_client(url, http_client=hc) as streams, \
        ClientSession(*streams[:2]) as s:
    sdk_init = await s.initialize()
    test_eq({t.name for t in (await s.list_tools()).tools}, {'fahrenheit','nap','crash'})
    sdk_res = await s.call_tool('fahrenheit', dict(celsius=100))
test_eq(sdk_res.content[0].text, '212.0')
sdk_init.serverInfo
```

```output
Implementation(name='demo', title=None, version='0.0.5', websiteUrl=None, icons=None)
```

In the other direction, our client calls an SDK FastMCP server. This setup returns SSE and creates a session id. The client sends the id with subsequent requests. After calling the tool, it ends the server session explicitly before closing its HTTP connection:

```python
import logging, uvicorn
from mcp.server.fastmcp import FastMCP
```

```python
logging.getLogger('mcp').setLevel(logging.WARNING)
fm = FastMCP('sdkdemo')
@fm.tool()
def double(x: int) -> int:
    "Twice `x`"
    return x*2

port2 = free_port()
sdk_task = asyncio.create_task(uvicorn.Server(uvicorn.Config(fm.streamable_http_app(), host='127.0.0.1', port=port2, log_level='warning')).serve())
for _ in range(100):
    try:
        with socket.create_connection(('127.0.0.1', port2), timeout=0.5): break
    except OSError: await asyncio.sleep(0.05)
async with MCPClient.http(f'http://127.0.0.1:{port2}/mcp') as c:
    test_eq(c.info['serverInfo']['name'], 'sdkdemo')
    assert c.tr.sess, 'SDK server should have minted a session id'
    dbl = await c.tools.double(x=21)
    await c.tr.delete()
    assert c.tr.sess is None
dbl
```

```output
[09/09/26 18:40:43] INFO     HTTP Request: POST                  _client.py:1740
                             http://127.0.0.1:56411/mcp                         
                             "HTTP/1.1 200 OK"                                  
                    INFO     HTTP Request: POST                  _client.py:1740
                             http://127.0.0.1:56411/mcp                         
                             "HTTP/1.1 202 Accepted"                            
                    INFO     HTTP Request: POST                  _client.py:1740
                             http://127.0.0.1:56411/mcp                         
                             "HTTP/1.1 200 OK"                                  
                    INFO     HTTP Request: POST                  _client.py:1740
                             http://127.0.0.1:56411/mcp                         
                             "HTTP/1.1 200 OK"                                  
'42'
```

## The mcpmini command

An MCP host needs a command to launch. `mcpmini tools.py` loads and serves a Python file without a wrapper script. The file stem names the server, and its docstring supplies the instructions.

A nonempty `__all__` selects the objects to serve. Without it, [`load_server`](core.md#load_server) selects functions defined in that module. Either way, it removes names beginning with `_`. Loading the file executes its top-level code.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L395)

### load\_server

```python
def load_server(
    path, # Python file whose public docmented functions become the tools
):
```

*An [`MCPServer`](core.md#mcpserver) for the file at `path`: named after it, instructed by its docstring, serving its functions*

This file defines a public converter, a private helper, and an import. With no `__all__`, only the converter becomes a tool. Imported helpers are not tools by default; an explicit `__all__` can include them:

```python
toolsfile = Path(tempfile.mkdtemp())/'weather.py'
toolsfile.write_text(""""Answer weather questions."
from json import dumps

def _secret(): pass

def celsius(
    fahrenheit:float, # Temperature to convert
)->float:
    "Convert Fahrenheit to Celsius"
    return (fahrenheit-32)*5/9
""")
wsrv = load_server(toolsfile)
test_eq((wsrv.name, list(wsrv.funcs), wsrv.instructions), ('weather', ['celsius'], 'Answer weather questions.'))
wsrv.specs
```

```output
[{'name': 'celsius',
  'description': 'Convert Fahrenheit to Celsius\n\nReturns:\n- type: number',
  'inputSchema': {'type': 'object',
   'properties': {'fahrenheit': {'description': 'Temperature to convert',
     'type': 'number'}},
   'required': ['fahrenheit']}}]
```

`call_parse` turns [`main`](core.md#main)'s docments into the CLI. Stdio is the default. HTTP deployment uses `--transport http`, `--host`, `--port`, and `--path`. Supply the token with `--token` or `$MCPMINI_TOKEN`; `--no-token` opts out of the non-loopback protection. `streamable-http` is another accepted transport spelling.

[source](https://github.com/AnswerDotAI/mcpmini/blob/main/mcpmini/core.py#L406)

### main

```python
def main(
    tools:str, # Python file whose public docmented functions are served
    transport:str='stdio', # 'stdio', or 'http' for streamable HTTP
    host:str='127.0.0.1', # Interface to bind, for http
    port:int=8000, # Port to bind, for http
    token:str=None, # Bearer token, for http; `$MCPMINI_TOKEN` if unset
    no_token:bool=False, # Serve http on a non-loopback interface openly, when auth lives elsewhere
    path:str='/mcp', # Endpoint path, for http
):
```

*Serve a Python file's docmented functions as an MCP server*

This time the client launches the installed `mcpmini` command with the tools file as its argument. We check that the instructions reach the client and that the converter returns the expected value:

```python
cmd = shutil.which('mcpmini')
assert cmd, 'mcpmini console script not installed: run `uv sync`'
async with MCPClient.stdio([cmd, str(toolsfile)]) as c:
    test_eq(c.info['instructions'], 'Answer weather questions.')
    freezing = await c.tools.celsius(fahrenheit=32)
freezing
```

```output
'0.0'
```

## A live client

SDK interoperability does not tell us whether a model host will discover and use the tool. This disabled example uses the Claude Agent SDK to run Claude Code headlessly. Claude launches `mcpmini`, discovers the converter, and calls it.

Checking the answer alone would miss a model doing the conversion itself. The assertion checks the actual `tool_use` name as well. These cells spend model tokens and do not run in automated tests.

```python
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
```

```python
logging.getLogger('claude_agent_sdk').setLevel(logging.WARNING)
with tempfile.TemporaryDirectory() as td:
    live_tools = Path(td)/'weather.py'
    live_tools.write_text(toolsfile.read_text())
    opts = ClaudeAgentOptions(model='haiku', max_turns=3, tools=[], setting_sources=[], strict_mcp_config=True,
        mcp_servers=dict(demo=dict(type='stdio', command=shutil.which('mcpmini'), args=[str(live_tools)])),
        allowed_tools=['mcp__demo__celsius'], system_prompt='Use the tools you are given.')
    msgs = [m async for m in query(prompt='Convert 212 fahrenheit to celsius with the celsius tool. Reply with only the number.', options=opts)]
    tus = [b.name for m in msgs if isinstance(m, AssistantMessage) for b in m.content if getattr(b,'name',None)]
    res = first(m.result for m in msgs if isinstance(m, ResultMessage))
    test_eq(tus, ['mcp__demo__celsius'])
    assert '100' in res
res
```

```output
'100.0'
```

The HTTP version supplies a URL and an `Authorization` header instead of a subprocess command. The server could also run on another machine. To record that connection in Claude Code, `claude mcp add --transport http` accepts the URL and `--header` option. This example still uses loopback and also spends model tokens.

```python
live_port = free_port()
live_task = asyncio.create_task(serve_mcp(wsrv, port=live_port, token='sesame'))
await asyncio.sleep(0.2)
hopts = ClaudeAgentOptions(model='haiku', max_turns=3, tools=[], setting_sources=[], strict_mcp_config=True,
    mcp_servers=dict(demo=dict(type='http', url=f'http://127.0.0.1:{live_port}/mcp', headers={'Authorization': 'Bearer sesame'})),
    allowed_tools=['mcp__demo__celsius'], system_prompt='Use the tools you are given.')
hmsgs = [m async for m in query(prompt='Convert 451 fahrenheit to celsius with the celsius tool. Reply with only the number.', options=hopts)]
htus = [b.name for m in hmsgs if isinstance(m, AssistantMessage) for b in m.content if getattr(b,'name',None)]
hres = first(m.result for m in hmsgs if isinstance(m, ResultMessage))
live_task.cancel()
test_eq(htus, ['mcp__demo__celsius'])
assert '232' in hres
hres
```

```output
'232.78'
```

## Cleanup

Cancel both loopback servers, wait for their tasks to finish, and remove the temporary tool scripts.

```python
for t in (server_task, sdk_task): t.cancel()
res = await asyncio.gather(server_task, sdk_task, return_exceptions=True)
for p in (serverfile, toolsfile): shutil.rmtree(p.parent, ignore_errors=True)
```
