Tutorial¶
Make a server of the Model Context Protocol with Pyjoyment.
A quick example-driven introduction to the servers of Pyjo.MCP.Server,
whose tools a language model calls, as Claude, through a client of MCP, as
Claude Code. A server is a route of an application of Pyjoyment, so
what the tutorial of Pyjoyment teaches
applies here too: the commands, the user agent, the tests and the servers.
A first server¶
A tool is a function. Its name, its description and the schema of its
arguments are those of the function: its name, the first paragraph of its
docstring, and its type hints, with the descriptions of the fields
:param of its docstring. The server is the action of a route, and
Pyjoyment.Plugin.AllowedHosts validates Host and Origin, which
the specification requires of a server on localhost, as a page of another
site could otherwise reach it through DNS rebinding.
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
server = Server(name='hello', version='1.0.0')
@server.tool
def greet(name: str) -> str:
"""Greet somebody by name.
:param name: Name of the person to greet.
"""
return f'Hello, {name}!'
# Host and Origin of localhost only, against DNS rebinding
plugin('AllowedHosts')
any('/mcp', server.to_action())
app.start()
The command daemon serves it, or pyjo-reload, which restarts it when a
file changes, and Claude Code connects to it over HTTP:
$ uv run pyjo-reload -l http://127.0.0.1:3000 hello.py
$ claude mcp add --transport http hello http://127.0.0.1:3000/mcp
Claude Code then lists the tool greet with its description and the schema
of its argument, and calls it when a conversation asks for a greeting. Every
request of MCP is a POST of JSON-RPC to the endpoint, with the revision of the
specification and the capabilities of the client in its _meta and in its
headers, as the protocol has no session:
curl http://127.0.0.1:3000/mcp \
-H 'MCP-Protocol-Version: 2026-07-28' -H 'Mcp-Method: tools/call' -H 'Mcp-Name: greet' \
-d '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "greet", "arguments": {"name": "Pyjo"},
"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}}}'
The response is the result of the tool, with the name and the version of the
server in its _meta:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "hello", "version": "1.0.0"}},
"content": [{"text": "Hello, Pyjo!", "type": "text"}],
"isError": false,
"resultType": "complete"
}
}
Schemas¶
The type hints are the inputSchema of the tool, as
parameters() of
Pyjo.JSON.Schema gives it: a parameter without a default is required,
a Literal is an enum, and Annotated adds a description or the
keywords of JSON Schema, as minimum and maximum. The annotation of
what the function returns is the outputSchema, here a list of
TypedDict, whose description is its docstring.
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
from typing import Annotated, Literal, TypedDict
server = Server(name='shop', version='1.0.0')
class Item(TypedDict):
"""An item of the shop."""
name: str
price: Annotated[float, 'Price in EUR']
stock: int
ITEMS = [
Item(name='Pyjo mug', price=12.5, stock=3),
Item(name='Pyjo shirt', price=25.0, stock=0),
Item(name='Pyjo sticker', price=1.5, stock=100),
]
@server.tool(annotations={'readOnlyHint': True})
def search(
query: str,
limit: Annotated[int, {'minimum': 1, 'maximum': 10}] = 5,
sort: Literal['name', 'price'] = 'name',
in_stock: bool = False,
) -> list[Item]:
"""Search the items of the shop.
:param query: Part of the name of an item, in any case.
:param limit: How many items at most.
:param sort: Order of the items.
:param in_stock: Only the items that are in stock.
"""
found = [item for item in ITEMS if query.lower() in item['name'].lower()]
if in_stock:
found = [item for item in found if item['stock']]
return sorted(found, key=lambda item: item[sort])[:limit]
plugin('AllowedHosts')
any('/mcp', server.to_action())
app.start()
A result of an outputSchema is the structuredContent of the result of
the tool, which a client validates, and its JSON the text of its content,
which the language model reads. A function that returns a string has no
outputSchema: the string is the text. annotations tell a client how the
tool behaves, as readOnlyHint of a tool that changes nothing, as hints that
the client weighs, not as guarantees.
The server validates the arguments with the inputSchema before it calls
the function, so the function gets the arguments that it declares. The values
are those of JSON, as a string of a date, which the function converts itself.
Errors¶
A tool has two kinds of errors. An error of its execution, as arguments that
are not valid or a date in the past, is a result with isError, whose text
the language model reads to call the tool again with other arguments: the
arguments that the inputSchema does not validate are one, and so is a
Pyjo.MCP.Tool.Error that the function raises. An error of the
protocol, as a tool that does not exist, is an error of JSON-RPC, and an
exception of the function is an error of the server, which the application
logs, and whose message the client does not see.
from Pyjo.MCP.Server import Server
from Pyjo.MCP.Tool import Error
from Pyjoyment.Lite import *
import datetime
from typing import Annotated
server = Server(name='flights', version='1.0.0')
@server.tool
def book(date: str, seats: Annotated[int, {'minimum': 1}] = 1) -> str:
"""Book seats of a flight.
:param date: Date of the flight, in the future, as YYYY-MM-DD.
:param seats: How many seats.
"""
try:
day = datetime.date.fromisoformat(date)
except ValueError:
raise Error.new(f'Invalid date {date}: expected YYYY-MM-DD.') from None
if day <= datetime.date.today():
raise Error.new(f'Invalid date {date}: the flight has to be in the future.')
if seats > 9:
raise RuntimeError('The booking system is down')
return f'Booked {seats} seats on {date}.'
plugin('AllowedHosts')
any('/mcp', server.to_action())
app.start()
Asynchronous tools¶
A tool can return a Pyjo.Promise or be a coroutine, as a function
async, which awaits the non-blocking Pyjo.UserAgent of the
application, so that the server answers other requests while the tool waits
for another service. Pyjo.DOM takes a web page apart:
from Pyjo.MCP.Server import Server
from Pyjo.MCP.Tool import Error
from Pyjoyment.Lite import *
server = Server(name='titles', version='1.0.0')
@server.tool(annotations={'readOnlyHint': True, 'openWorldHint': True})
async def title(url: str) -> str:
"""The title of a web page.
:param url: URL of the page.
"""
# Non-blocking, so the server answers other requests while the page loads
tx = await app.ua.get_p(url)
if (res := tx.result).is_error:
raise Error.new(f'The page answered {res.code} {res.message}')
if (element := res.dom().at('title')) is None:
raise Error.new('The page has no title')
return element.text
plugin('AllowedHosts')
any('/mcp', server.to_action())
app.start()
The example examples/weather.py of the distribution is a gateway to the
weather of Open-Meteo, made this way, with the tools find_places,
current_weather, forecast and hourly_forecast.
Context¶
A tool with context gets the Context of the
request before its arguments, with what the _meta of the request tells, as
the name of the client and the revision of the protocol, and the
Pyjoyment.Controller of the request of HTTP, with its headers and the
helpers of the application.
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
server = Server(name='context', version='1.0.0')
@server.tool(context=True)
def whoami(context) -> str:
"""Tell who calls the server."""
client = context.client_info.get('name', 'an unknown client')
agent = context.controller.req.headers.user_agent
return f'{client} {context.protocol_version}, with {agent}'
plugin('AllowedHosts')
any('/mcp', server.to_action())
app.start()
The protocol is stateless: a server does not keep anything of a client between its requests. A tool that needs a state, as a basket of a shop, returns a handle of it, which the language model passes to the next tool.
Progress¶
A tool that takes long tells the client how far it is with
notify_progress(), and what it does with
notify_log(), before its result. The client
asks for them in the _meta of its request, with a progressToken and
the lowest level of the log messages that it wants, and the notifications that
it did not ask for go nowhere. Over Streamable HTTP, the first notification
turns the response into a stream of events, which ends with the result, when
the client accepts one, and which a comment keeps open while the tool is
silent. A client that closes the connection before the result cancels the
request, which stops a tool that is a coroutine where it waits, with the
requests of Pyjo.UserAgent that it waits for, and which
is_cancelled tells another one. Over the
transport stdio, the notifications are messages of the same stream:
import Pyjo.Promise
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
server = Server(name='counter', version='1.0.0')
@server.tool(context=True)
async def count(context, to: int) -> int:
"""Count slowly to a number.
:param to: The number to count to.
"""
context.notify_log('info', f'Counting to {to}')
counted = 0
while counted < to and not context.is_cancelled:
await Pyjo.Promise.timer(0.1)
counted += 1
context.notify_progress(counted, to, f'Counted to {counted}')
return counted
plugin('AllowedHosts')
hook('before_server_start', server.to_stdio())
any('/mcp', server.to_action())
app.start()
Prompts and resources¶
A tool is what the language model calls; a prompt and a resource are what the
user picks. A prompt is a template of messages, as a task that the user starts
with its arguments, and a resource is data of the server, as a document or a
configuration, which the client reads by its URI and gives the language model
as its context. Both are functions too: the name and the description of a
prompt are those of its function, and its arguments are the parameters, whose
values are strings, of which those without a default are required. A resource
has its URI, and its media type, text/plain by default.
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
from typing import Literal
server = Server(name='reviewer', version='1.0.0')
STYLE = """\
# Style guide
* Single quotes for strings.
* Lines of 120 characters at most.
"""
@server.resource('docs://style', mime_type='text/markdown')
def style() -> str:
"""The style guide of the project."""
return STYLE
@server.resource('config://limits', mime_type='application/json')
def limits() -> dict:
"""The limits that the linter checks."""
return {'line_length': 120}
@server.prompt(title='Code review')
def review(code: str, focus: Literal['bugs', 'style'] = 'bugs') -> list:
"""Review a piece of code against the style guide.
:param code: The code to review.
:param focus: What to look for, as bugs or style.
"""
return [
{
'role': 'user',
'content': {
'type': 'resource',
'resource': {'uri': 'docs://style', 'mimeType': 'text/markdown', 'text': STYLE},
},
},
{'role': 'user', 'content': {'type': 'text', 'text': f'Review this code for {focus}:\n{code}'}},
]
plugin('AllowedHosts')
hook('before_server_start', server.to_stdio())
any('/mcp', server.to_action())
app.start()
A prompt returns a string, which is one message of the user, or the messages
themselves, here with the style guide embedded as a resource before the
question. A resource returns a string, which is its text, bytes,
which are its blob in Base64, or another value, whose JSON is the text, as
the limits here. Like a tool, both can return a Pyjo.Promise or be
coroutines, and get the Context of the request with
context. The values of an argument with Literal, as focus here, or
with an Enum, are the completions that completion/complete gives a
client while the user types it.
Claude Code lists the prompts as commands, as /mcp__reviewer__review,
which ask for the arguments, and the resources as mentions, as
@reviewer:docs://style, which put their contents into the conversation.
Resource templates¶
The resources that a server cannot list, as the files of a directory, are a
resource template, a URI Template of RFC 6570: the client lists the
templates with resources/templates/list, makes a URI of one of them, and
reads it with resources/read. A URI with variables is a template, whose
function gets their values as keyword arguments, here the path of a file of
the directory of the script:
import Pyjo.File
import Pyjo.JSON.RPC
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
import os
server = Server(name='project', version='1.0.0')
root = Pyjo.File.curfile().dirname()
def project_paths(value: str, arguments: dict[str, str]) -> list[str]:
"""The paths of the files of the project that start with the value."""
paths = (str(file.to_rel(root)).replace(os.sep, '/') for file in root.list_tree())
return sorted(path for path in paths if path.startswith(value))
@server.resource('file:///project/{+path}', mime_type='text/x-python', complete={'path': project_paths})
def project_file(path: str) -> str:
"""A file of the project, by its path in the project."""
file = root.child(*path.split('/'))
if not os.path.isfile(file):
uri = f'file:///project/{path}'
raise Pyjo.JSON.RPC.Error.new(Pyjo.JSON.RPC.INVALID_PARAMS, 'Resource not found', {'uri': uri})
return file.slurp('UTF-8')
plugin('AllowedHosts')
hook('before_server_start', server.to_stdio())
any('/mcp', server.to_action())
app.start()
The values come from the client, so a URI whose value has a segment ..,
an absolute path or the character NUL, which would read a file outside of the
directory, has no resource, unless the template is made with safe=False. A
function that finds nothing raises the error of JSON-RPC itself. A resource
that the server lists comes before a template that matches its URI too, and
the templates are tried in their order.
The option complete gives the completions of the values of the variables,
or of the arguments of a prompt: a list of the values, which the server filters
by what the user has typed, or a function, as here, that gets it and the values
of the other variables, and returns the values that fit, of which the server
gives at most 100.
Subscriptions¶
The lists of a server and its resources can change while it runs. A client
that wants to know opens a subscription with subscriptions/listen, a
request that stays in progress, with the notifications that it asks for: of a
change of the list of the tools, of the prompts or of the resources, and of a
change of a resource of its URI. The application tells the server what changed
with notify_list_changed() and
notify_resource_updated(), and declares
that it does with list_changed and subscribe, which
server/discover tells the clients:
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
server = Server(name='notes', version='1.0.0')
server.list_changed = server.subscribe = True
notes: list[str] = []
@server.resource('notes://all', mime_type='text/markdown')
def all_notes() -> str:
"""All the notes, as a list of Markdown."""
return ''.join(f'* {note}\n' for note in notes)
@server.tool
def add_note(text: str) -> int:
"""Add a note, which is a resource of its own too, and return its number.
:param text: The text of the note.
"""
notes.append(text)
number = len(notes)
server.resource(f'notes://{number}', lambda: text, name=f'note_{number}', description=f'Note {number}.')
server.notify_list_changed('resources')
server.notify_resource_updated('notes://all')
return number
plugin('AllowedHosts')
hook('before_server_start', server.to_stdio())
any('/mcp', server.to_action())
app.start()
A notification tells only what changed, so the client reads the list or the
resource again. Over Streamable HTTP, a subscription is a stream of events,
which a comment keeps open while nothing changes, and which the server ends
with a response when it stops gracefully. Over the transport stdio, its
messages share the stream with the others, and the client cancels it with
notifications/cancelled. The subscriptions are those of a worker, a
process of prefork or a thread of prethread, so the worker that changes
a list notifies only its own clients.
Input¶
A tool, a prompt or a resource can ask the client for input before it
answers: the user, with a form of elicitation/create, the language model
of the client, with sampling/createMessage, or the directories that the
client works on, with roots/list. The server keeps no connection open for
it: the result input_required gives the client the requests, and the
client sends the same request again with their responses, a round of the
request each time. A function asks with
elicit(),
sample() or
list_roots() of its context, with a key that
names the request in every round, and gets the response once the client has
given it:
from Pyjo.MCP.Server import Server
from Pyjo.MCP.Tool import Error
from Pyjoyment.Lite import *
server = Server(name='files', version='1.0.0')
files = {'notes.txt': 'Buy milk, eggs and bread.', 'todo.txt': 'Write the tutorial.'}
@server.tool(context=True)
def delete(context, name: str) -> str:
"""Delete a file, once the user confirms it.
:param name: The name of the file.
"""
if name not in files:
raise Error(f'No such file: {name}')
if context.elicit('confirm', f'Delete {name}?')['action'] != 'accept':
return f'Kept {name}'
del files[name]
return f'Deleted {name}'
@server.tool(context=True)
def summarize(context, name: str) -> str:
"""Summarize a file with the language model of the client.
:param name: The name of the file.
"""
if name not in files:
raise Error(f'No such file: {name}')
result = context.sample('summary', f'Summarize in a few words:\n{files[name]}', 50)
return result['content']['text']
app.secrets = ['s3cret']
plugin('AllowedHosts')
hook('before_server_start', server.to_stdio())
any('/mcp', server.to_action())
app.start()
The function runs again from its beginning in each round, so what it does
before it asks has to be safe to repeat, as here deleting the file only once
the user confirms. The responses of the rounds before, and the values that the
function keeps in state, come back with the
requestState of the result, which the secrets of the application sign,
as they sign its cookies, and which expires after ten minutes: the client can
read it, but not change it. A client that does not declare the capability of
a request, elicitation, sampling or roots, gets the error
-32021 instead.
Security¶
A server on localhost binds to 127.0.0.1, not to all the interfaces,
and Pyjoyment.Plugin.AllowedHosts takes the hosts of a deployment with
a name of its own. With hook=False, it checks only the routes under its
helper allowed_hosts, as here the endpoint of MCP, under a callback that
checks the bearer token of the client too, while the other pages of the
application stay open:
import Pyjoyment.Plugin.AllowedHosts
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
import hmac
import os
server = Server(name='secure', version='1.0.0')
@server.tool
def secret() -> str:
"""A secret, for the clients with the token only."""
return 'The cake is a lie.'
# A page of the application, which anybody can see
get('/', {'text': 'The MCP endpoint is /mcp.'})
# The hosts of localhost and of the deployment, checked only for the routes under the helper allowed_hosts
plugin('AllowedHosts', hosts=[*Pyjoyment.Plugin.AllowedHosts.HOSTS, 'mcp.example.com'], hook=False)
TOKEN = os.environ.get('MCP_TOKEN', '')
def authorized(c):
# Host and Origin first, then the bearer token, as an MCP client sends it in Authorization
if not c.allowed_hosts():
return False
sent = c.req.headers.authorization or ''
if TOKEN and hmac.compare_digest(sent, f'Bearer {TOKEN}'):
return True
c.res.headers.header('WWW-Authenticate', 'Bearer')
c.render(json={'error': 'Unauthorized'}, status=401)
return False
# The routes after under are its own, so it comes last
under('/mcp', authorized)
any('/', server.to_action())
app.start()
Claude Code sends the token with the header that it is given:
$ claude mcp add --transport http secure http://127.0.0.1:3000/mcp --header 'Authorization: Bearer sesame'
Standard input and output¶
The transport stdio needs no port, no Host and no token: the client
starts the server as its child process, and sends a message of JSON-RPC on
each line of its standard input, whose responses come on the lines of its
standard output. to_stdio() is the hook
that serves the tools so, when the command
stdio starts the application, and
the same application still serves Streamable HTTP with daemon:
from Pyjo.MCP.Server import Server
from Pyjoyment.Lite import *
server = Server(name='hello', version='1.0.0')
@server.tool
def greet(name: str) -> str:
"""Greet somebody by name.
:param name: Name of the person to greet.
"""
app.log.info(f'Greeting {name}')
return f'Hello, {name}!'
# Host and Origin of localhost only, against DNS rebinding
plugin('AllowedHosts')
any('/mcp', server.to_action())
# The transport stdio, of the command stdio
hook('before_server_start', server.to_stdio())
app.start()
The log of the application goes to the standard error, as anything else that the tools print, so that only the messages of MCP are on the standard output. The server ends when the client closes its standard input, once the requests in progress have their responses. Claude Code starts it with the command:
$ claude mcp add hello -- uv run python stdio.py stdio
Testing¶
Pyjo.MCP.Test tests a server without starting it, as
Pyjo.Test.Pyjo tests any application of Pyjoyment, with the requests
that Pyjo.MCP.Client sends: the _meta and the headers of MCP are
made for each request, the arguments of a tool are keyword arguments after its
name, and the assertions check the result, its text, its structuredContent
and isError, the tools of tools/list, the notifications of a
subscription and the errors of JSON-RPC:
import Pyjo.MCP.Test
from Pyjo.File import curfile
from Pyjo.Test import *
t = Pyjo.MCP.Test.new(curfile().sibling('hello.py'))
with subtest('Greeting'):
t.call_ok('greet', name='Pyjo').status_is(200).text_content_is('Hello, Pyjo!').is_error_is(False)
with subtest('Without a name'):
t.call_ok('greet').status_is(200).is_error_is(True).text_content_like(r'/name: Missing property')
with subtest('Tools'):
t.list_tools_ok().status_is(200).tool_is('greet', '/inputSchema/required', ['name'])
done_testing()
$ uv run python -m Pyjo.Prove hello_test.py
More¶
The API of the server, of the tools, of the prompts, of the resources, of the
resource templates, of the client and of the tests is in
Pyjo.MCP.Server, Pyjo.MCP.Tool, Pyjo.MCP.Prompt,
Pyjo.MCP.Resource, Pyjo.MCP.ResourceTemplate,
Pyjo.MCP.Client and Pyjo.MCP.Test, and the deployment of an application, with the servers
of Pyjoyment and a container, in its cookbook.