Pyjo.MCP.Server - Server of MCP

from Pyjo.MCP.Server import Server

server = Server(name='calculator', version='1.0.0')

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

@server.prompt
def explain(expression: str) -> str:
    """Explain an arithmetic expression step by step."""
    return f'Explain step by step how to compute {expression}.'

@server.resource('calculator://precision', mime_type='application/json')
def precision() -> dict:
    """The precision of the numbers of the calculator."""
    return {'digits': 15}

# Or import the module, as in Google Python Style Guide

import Pyjo.MCP.Server

server = Pyjo.MCP.Server.new(name='calculator', version='1.0.0', instructions='Arithmetic for the model.')
server.tool('add', lambda a, b: a + b, input_schema={'type': 'object', 'properties': {'a': {}, 'b': {}}})

# Pyjoyment.Lite, with the validation of Host and Origin
plugin('AllowedHosts')
any('/mcp', server.to_action())

# Pyjoyment
app.plugin('AllowedHosts')
app.routes.any('/mcp').to(cb=server.to_action())

# The transport stdio too, of the command stdio
app.hook('before_server_start', server.to_stdio())

Pyjo.MCP.Server is a server of the Model Context Protocol, of the revision Pyjo.MCP.PROTOCOL_VERSION of the specification, with the methods server/discover, tools/list and tools/call, whose tools are Pyjo.MCP.Tool objects, prompts/list and prompts/get, whose prompts are Pyjo.MCP.Prompt objects, resources/list, resources/templates/list and resources/read, whose resources are Pyjo.MCP.Resource and Pyjo.MCP.ResourceTemplate objects, and completion/complete, which completes the values of their arguments and variables. The protocol is stateless: each request carries its revision and the capabilities of its client in its _meta, which the server checks, and a result carries the name and the version of the server in its own _meta.

A client that wants to know of the changes of the server opens a subscription with subscriptions/listen, a request that stays in progress, whose stream gets the notifications of notify_list_changed() and notify_resource_updated() that the client asks for, until the client cancels it or the server stops.

A tool, a prompt or a resource that needs input of the client, of the user, of its language model or of its roots, asks for it with Context.elicit(), Context.sample(), Context.list_roots() or Context.input(), and the server answers with the result input_required of the requests, whose responses come with the same request again, in the rounds of a multi round-trip request, with the responses of the rounds before in its requestState, which secrets sign.

The requests come over Streamable HTTP, the transport of to_action(), an action of a route of Pyjoyment, which answers each request with a JSON object, or with a stream of events when the request sends notifications before its result, as its progress, and the client accepts one. The specification requires the validation of Origin of a server on localhost, against DNS rebinding, which Pyjoyment.Plugin.AllowedHosts does, for the whole application or the routes under its helper.

The requests come over the transport stdio too, a message of JSON-RPC on each line of the standard input and output, which to_stdio() serves when the command stdio of Pyjoyment starts the application, and the log goes to the standard error. serve() serves any other stream of messages, and dispatch_p() handles a message of any other transport.

See also

Pyjo.MCP.Tool, Pyjo.MCP.Prompt, Pyjo.MCP.Resource, Pyjo.MCP.ResourceTemplate, Pyjo.JSON.RPC, Pyjoyment.Plugin.AllowedHosts, Pyjo.MCP.

Classes

class Pyjo.MCP.Server.Context(controller: Pyjoyment.Controller.object | None = None, client: Client | None = None, log: Pyjo_Log | None = None, app: Any = None)[source]

The context of a request of MCP, with what its _meta tells, which a tool that asks for it gets before its arguments, and the notifications that the tool sends to the client before its result.

@server.tool(context=True)
def whoami(context) -> str:
    return context.client_info.get('name', 'unknown')

Events

cancelled

@context.on('cancelled')
def cancelled(context):
    ...

Emitted once when the client abandons the request, as when it closes the connection of a response of Streamable HTTP before the result, or sends notifications/cancelled of the request over the transport stdio, so that a tool that runs long stops. A coroutine of a tool, or the promise that the tool returns, is cancelled by the server, with cancellable(), and another one subscribes to the event.

id = Pyjo.IOLoop.recurring(1, lambda: ...)
context.on('cancelled', lambda context: Pyjo.IOLoop.remove(id))
__init__(controller: Pyjoyment.Controller.object | None = None, client: Client | None = None, log: Pyjo_Log | None = None, app: Any = None) → None[source]
context = Pyjo.MCP.Server.Context.new()
context = Pyjo.MCP.Server.Context.new(c)
context = Pyjo.MCP.Server.Context.new(client=client, log=app.log, app=app)

Construct a new Context object.

app
app = context.app

The application of Pyjoyment of the request, the one of the controller or of the transport stdio, whose secrets sign the state of the request by default, or None.

cancel() → Self[source]
context = context.cancel()

Mark the request as abandoned, and emit the event cancelled, once.

cancellable(promise: Pyjo_Promise) → Pyjo_Promise[source]
promise = context.cancellable(promise)

Cancel the promise with Pyjo.Promise.Pyjo_Promise.cancel() when the client abandons the request, and return a promise of its value, which the server does for the promise or the coroutine of a tool, a prompt, a resource and a completion: a coroutine gets the exception of the cancellation of the reactor, as asyncio.CancelledError, where it waits, so that its finally blocks run, and a request of Pyjo.UserAgent.Pyjo_UserAgent.start_p() that it waits for closes its connection. That cancellation rejects the returned promise with an error of JSON-RPC, not of the server, which is not logged, as nothing reads its response anymore.

# A coroutine that stops where it waits when the client goes away
async def slow() -> str:
    await Pyjo.Promise.timer(60)
    return 'Done'

promise = context.cancellable(Pyjo.Promise.new(slow()))
client
client = context.client

The Pyjo.JSON.RPC.Client of the peer of a stream of messages, as the transport stdio, whose requests go to the client of MCP on the same stream, or None for Streamable HTTP.

client_capabilities: dict[str, Any]
capabilities = context.client_capabilities

The capabilities of the client, as the request declares them.

client_info: dict[str, Any]
info = context.client_info

The name and the version of the client, as the request tells them, or an empty dict.

controller
c = context.controller

The Pyjoyment.Controller of the request of HTTP, or None for another transport.

elicit(key: str, message: str, schema: dict[str, Any] | None = None) → dict[str, Any][source]
result = context.elicit('confirm', 'Delete the file?')
result = context.elicit('name', 'Who are you?', {'type': 'object', 'properties': {'name': {'type': 'string'}}})

Ask the user for input with a form, elicitation/create of the key, as input() does, and return the result of the client, whose action is accept, decline or cancel, with the content of the form when the user accepts. The schema of the form is an object without properties by default, a confirmation.

if context.elicit('confirm', f'Delete {path}?')['action'] != 'accept':
    return 'Cancelled'
id: Any
id = context.id

The id of the request of JSON-RPC, which the messages of its subscription name, or None for a notification.

input(requests: dict[str, dict[str, Any]]) → dict[str, Any][source]
responses = context.input({'roots': {'method': 'roots/list'}})

Return the responses of the client to the requests, by their keys, or raise InputRequired of the requests that it has not answered yet, which the server answers with the result input_required, so that the client asks the user or its language model, and sends the request again with their responses. The function then runs again from its beginning, and gets them, so what it does before it asks for input has to be safe to repeat. A key names the same request in every round. A request of a capability that the client does not declare, elicitation, sampling or roots, raises the error -32021 of JSON-RPC.

# Two questions at once
responses = context.input(
    {
        'name': {'method': 'elicitation/create', 'params': {'message': 'Name?', 'requestedSchema': schema}},
        'roots': {'method': 'roots/list'},
    }
)
input_responses: dict[str, Any]
responses = context.input_responses

The responses of the client to the requests of input(), by their keys, of all the rounds of the request so far: the inputResponses of the request, and those of the rounds before it, which its requestState keeps.

property is_cancelled: bool[source]
boolean = context.is_cancelled

Check if the client abandoned the request, for a tool that cannot subscribe to the event cancelled and checks it instead.

list_roots(key: str = 'roots') → dict[str, Any][source]
result = context.list_roots()
result = context.list_roots('workspace')

Ask the client for its roots, roots/list of the key, roots by default, as input() does, and return the result of the client, whose roots are the directories and the files that the server may work on.

paths = [root['uri'] for root in context.list_roots()['roots']]
log
log = context.log

The Pyjo.Log of the errors of the server of a request without a controller, as the one of the application for the transport stdio, or None.

log_level: str | None
level = context.log_level

The lowest level of the log messages that the client wants of the request, as its _meta tells it, or None for none.

meta: dict[str, Any]
meta = context.meta

The _meta of the request.

notify(method: str, params: dict[str, Any] | None = None) → bool[source]
boolean = context.notify('notifications/message', {'level': 'info', 'data': 'Hello'})

Send a notification of JSON-RPC to the client, before the result of the request, and return whether it was sent: not for a request that the client abandoned, nor without a stream.

notify_log(level: str, data: Any) → bool[source]
boolean = context.notify_log('info', 'Fetching the forecast')
boolean = context.notify_log('error', {'code': 23})

Send a log message of the level, debug, info, notice, warning, error, critical, alert or emergency, as notifications/message, if the client wants the messages of the level, as log_level tells, and return whether it was sent.

notify_progress(progress: float, total: float | None = None, message: str | None = None) → bool[source]
boolean = context.notify_progress(1)
boolean = context.notify_progress(1, 3, 'Fetched the first page')

Send the progress of the request, as notifications/progress, if the client asked for it with a progress_token, and return whether it was sent.

progress_token: Any
token = context.progress_token

The progressToken of the _meta of the request, which the notifications of its progress name, or None for none.

protocol_version: str | None
version = context.protocol_version

The revision of the specification of the request.

sample(key: str, messages: str | list[dict[str, Any]], max_tokens: int, **params: Any) → dict[str, Any][source]
result = context.sample('summary', 'Summarize the file.', 100)
result = context.sample('summary', messages, 100, systemPrompt='You are terse.')

Ask the language model of the client for a message, sampling/createMessage of the key, as input() does, with the messages of the conversation, a string for one message of the user, the maximum number of tokens, and the other parameters of the request by their names in the specification, and return the result of the client, with the role, the content and the model of the message.

text = context.sample('haiku', f'Write a haiku about {topic}.', 50)['content']['text']
state: dict[str, Any]
state = context.state
context.state['total'] = 42

Values of JSON that a function keeps for the next round of the request, as the result of a long computation before it asks for input, which the signed requestState of the result input_required gives the client, and the client gives back. The client can read them, but not change them.

status: int | None
status = context.status

The status of the response of HTTP of an error, which the request sets, or None for the one of its code.

stream: Callable[[dict[str, Any]], Any] | None
cb = context.stream
context.stream = lambda notification: ...

The function of the transport that sends a notification of the request to the client, as an event of the stream of the response of Streamable HTTP, or a message of the transport stdio, or None, where the notifications go nowhere, as for a client of Streamable HTTP that does not accept a stream of events.

exception Pyjo.MCP.Server.InputRequired(requests: dict[str, dict[str, Any]])[source]

The exception of Context.input() of a request whose input the client has not given yet, which the server answers with the result input_required of its requests. A function lets it go, as an except Exception that catches it would keep the server from asking.

try:
    answer = context.elicit('confirm', 'Delete the file?')
except InputRequired:
    raise
except Exception:
    ...
__init__(requests: dict[str, dict[str, Any]]) → None[source]
__weakref__

list of weak references to the object

requests
requests = e.requests

The requests of the input, by their keys, as inputRequests gives them.

class Pyjo.MCP.Server.Pyjo_MCP_Server(name: str = 'Pyjo.MCP', version: str = '1.0.0', instructions: str | None = None)[source]

Pyjo.MCP.Server inherits all events and methods from Pyjo.EventEmitter and implements the following new ones.

Events

exception

@server.on('exception')
def exception(server, e, context):
    ...

Emitted when a tool raises an exception that is not a Pyjo.MCP.Tool.Error, an error of the server, which the response does not tell, with the Context of the request. The action of to_action() logs it with the log of the application too.

server.on('exception', lambda server, e, context: print(f'Failed: {e}'))
__init__(name: str = 'Pyjo.MCP', version: str = '1.0.0', instructions: str | None = None) → None[source]
server = Pyjo.MCP.Server.new()
server = Pyjo.MCP.Server.new(name='calculator', version='1.0.0', instructions='Arithmetic.')

Construct a new Pyjo.MCP.Server object.

cache_scope
scope = server.cache_scope
server.cache_scope = 'private'

Who may cache the results of server/discover and tools/list, public by default, or private for the tools of the user of the request.

cache_ttl
ttl = server.cache_ttl
server.cache_ttl = 300000

How long a client may cache the results of server/discover and tools/list, in milliseconds, 0 by default.

dispatch_p(message: Any, context: Context | None = None) → Pyjo_Promise[source]
promise = server.dispatch_p(request)
promise = server.dispatch_p(b'{"jsonrpc": "2.0", "method": "tools/list", ...}', context)

Dispatch a request or a notification of JSON-RPC, as Pyjo.JSON decodes it, or the JSON of one, and return a Pyjo.Promise of the response, or of None for a notification, as dispatch_p() does. A batch, which MCP does not have, and a request with the id of null, which MCP does not allow, are invalid requests.

heartbeat: float
interval = server.heartbeat
server.heartbeat = 15

How often a stream of events of Streamable HTTP, as a subscription or a tool that runs long, sends a comment, with the helper heartbeat of Pyjoyment, which keeps a connection without notifications from being closed by a proxy, in seconds, 30 by default, or 0 for never.

instructions
instructions = server.instructions
server.instructions = 'Arithmetic for the model.'

How a language model uses the server, which server/discover gives, or None.

list_changed
boolean = server.list_changed
server.list_changed = True

Whether server/discover declares listChanged of the tools, the prompts and the resources, a promise that the application calls notify_list_changed() when it changes a list, false by default.

name
name = server.name
server.name = 'calculator'

The name of the server, Pyjo.MCP by default.

notify_list_changed(kind: str) → int[source]
count = server.notify_list_changed('tools')
count = server.notify_list_changed('prompts')
count = server.notify_list_changed('resources')

Send notifications/tools/list_changed, or the one of the prompts or of the resources, to the subscriptions that want it, after a change of tools, prompts, resources or resource_templates, and return how many got it. The subscriptions are those of the process and of the thread, as each worker of a server that has several has its own.

server.tools = [tool for tool in server.tools if tool.name != 'add']
server.notify_list_changed('tools')
notify_resource_updated(uri: str) → int[source]
count = server.notify_resource_updated('file:///project/README.md')

Send notifications/resources/updated of the URI to the subscriptions that want it, after a change of the contents of the resource, which the client reads again, and return how many got it, as notify_list_changed() does.

prompt(name: F, cb: None = None) → F[source]
prompt(name: str | None = None, cb: None = None, **options: Any) → Callable[[F], F]
prompt(name: str, cb: F, **options: Any) → F
cb = server.prompt('review', lambda code: f'Review this code:\n{code}')
cb = server.prompt('review', lambda context, code: ..., context=True)

Add a prompt, a Pyjo.MCP.Prompt of the function with the options of its constructor, and return the function. Without a function, it is a decorator, with the name of the prompt or of the function.

@server.prompt
def review(code: str, language: str = 'Python') -> str:
    """Review a piece of code."""
    return f'Review this {language} code:\n{code}'

@server.prompt('code_review', title='Code review')
def code_review(code: str) -> str:
    """Review a piece of code."""
    return f'Review this code:\n{code}'
prompts: list[Pyjo_MCP_Prompt]
prompts = server.prompts

The Pyjo.MCP.Prompt objects of the server, in the order of prompts/list.

resource(uri: str, cb: None = None, **options: Any) → Callable[[F], F][source]
resource(uri: str, cb: F, **options: Any) → F
cb = server.resource('file:///project/README.md', lambda: '# Project', mime_type='text/markdown')
cb = server.resource('config://app', lambda context: ..., context=True)
cb = server.resource('notes://{number}', lambda number: ...)

Add a resource of the URI, a Pyjo.MCP.Resource of the function with the options of its constructor, and return the function. A URI Template of RFC 6570 with variables adds a resource template, a Pyjo.MCP.ResourceTemplate, whose function gets their values as keyword arguments. Without a function, it is a decorator.

@server.resource('file:///project/README.md', mime_type='text/markdown')
def readme() -> str:
    """The documentation of the project."""
    return '# Project'

@server.resource('notes://{number}')
def note(number: str) -> str:
    """A note, by its number."""
    return notes[int(number) - 1]
resource_templates: list[Pyjo_MCP_ResourceTemplate]
templates = server.resource_templates

The Pyjo.MCP.ResourceTemplate objects of the server, in the order of resources/templates/list, in which resources/read tries them for a URI that no resource has.

resources: list[Pyjo_MCP_Resource]
resources = server.resources

The Pyjo.MCP.Resource objects of the server, in the order of resources/list.

secrets: list[str] | None
secrets = server.secrets
server.secrets = ['passw0rd']

The secrets that sign the requestState of a request that needs input, the first one the new states and all of them the ones that come back, so that a secret can be rotated, or None for the secrets of the application of the request, as its signed cookies have them.

serve(peer: Any, log: Pyjo_Log | None = None, app: Any = None) → Client[source]
client = server.serve(messages)
client = server.serve(messages, log=app.log, app=app)

Serve the methods to a peer on a stream of messages in both directions, as a Pyjo.IOLoop.Messages object, and return the Pyjo.JSON.RPC.Client of the peer, as serve() does, with the rules of dispatch_p() and a Context of its own for each request, whose client is the one of the peer, whose log gets the errors of the server, and whose app is the application. notifications/cancelled of the peer cancels the Context of its request, which gets no response then, and the end of the input of the peer ends its subscriptions gracefully, with their responses.

# The transport stdio, a message on each line of the standard input and output
messages = Pyjo.IOLoop.Messages.new(Pyjo.IOLoop.Stdio.new())
server.serve(messages)
messages.start()
state_timeout
timeout = server.state_timeout
server.state_timeout = 3600

How many seconds the requestState of a request that needs input is valid, 600 by default, after which the client has to send the request again from its first round.

subscribe
boolean = server.subscribe
server.subscribe = True

Whether server/discover declares subscribe of the resources, a promise that the application calls notify_resource_updated() when a resource changes, false by default.

to_action() → Callable[[Pyjoyment.Controller.object], Any][source]
action = server.to_action()

The action of a route of Pyjoyment, the endpoint of MCP of Streamable HTTP, which takes a request of JSON-RPC in the body of a POST and renders its response in JSON, 202 Accepted without a body for a notification, 405 Method Not Allowed for another method of HTTP, and 400 Bad Request for a header of MCP that does not match the body, as MCP-Protocol-Version, Mcp-Method, Mcp-Name and Mcp-Param-{name}, or a request that is not valid. The first notification of the request, of Context.notify(), turns the response into a stream of events, text/event-stream, where the Accept of the request has it, with the notifications and then the response, with a comment every heartbeat seconds, and a connection that closes before the result cancels the Context. A subscription of subscriptions/listen is such a stream, which needs the Accept and stays open, until the client closes the connection, or until the event loop stops gracefully, which ends the subscription with its response.

# Pyjoyment.Lite
any('/mcp', server.to_action())

# Pyjoyment
app.routes.any('/mcp').to(cb=server.to_action())
to_stdio() → Callable[[Any, Any], None][source]
hook = server.to_stdio()

The hook before_server_start of an application of Pyjoyment, the transport stdio, which serves the methods with serve() on the standard input and output of Pyjo.Server.Stdio, a message of JSON-RPC on each line, when the command stdio starts the application, and does nothing for another server, so that the same application serves Streamable HTTP with daemon.

# Pyjoyment.Lite
hook('before_server_start', server.to_stdio())

# Pyjoyment
app.hook('before_server_start', server.to_stdio())
tool(name: F, cb: None = None) → F[source]
tool(name: str | None = None, cb: None = None, **options: Any) → Callable[[F], F]
tool(name: str, cb: F, **options: Any) → F
cb = server.tool('add', lambda a, b: a + b, input_schema={'type': 'object'})
cb = server.tool('whoami', lambda context: context.client_info.get('name'), context=True)

Add a tool, a Pyjo.MCP.Tool of the function with the options of its constructor, and return the function. Without a function, it is a decorator, with the name of the tool or of the function.

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

@server.tool('math.multiply', title='Multiplication', annotations={'readOnlyHint': True})
def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b
tools: list[Pyjo_MCP_Tool]
tools = server.tools

The Pyjo.MCP.Tool objects of the server, in the order of tools/list.

version
version = server.version
server.version = '2.0.0'

The version of the server, 1.0.0 by default.