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
_metatells, 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/cancelledof 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, withcancellable(), 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
Contextobject.
- app¶
app = context.app
The application of
Pyjoymentof the request, the one of the controller or of the transport stdio, whosesecretssign the state of the request by default, orNone.
- 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, asasyncio.CancelledError, where it waits, so that itsfinallyblocks run, and a request ofPyjo.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.Clientof the peer of a stream of messages, as the transport stdio, whose requests go to the client of MCP on the same stream, orNonefor 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.Controllerof the request of HTTP, orNonefor 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/createof the key, asinput()does, and return the result of the client, whoseactionisaccept,declineorcancel, with thecontentof 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
idof the request of JSON-RPC, which the messages of its subscription name, orNonefor 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
InputRequiredof the requests that it has not answered yet, which the server answers with the resultinput_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,samplingorroots, raises the error-32021of 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: theinputResponsesof the request, and those of the rounds before it, which itsrequestStatekeeps.
- 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
cancelledand 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/listof the key,rootsby default, asinput()does, and return the result of the client, whoserootsare 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.Logof the errors of the server of a request without a controller, as the one of the application for the transport stdio, orNone.
- log_level: str | None¶
level = context.log_level
The lowest level of the log messages that the client wants of the request, as its
_metatells it, orNonefor none.
- meta: dict[str, Any]¶
meta = context.meta
The
_metaof 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,alertoremergency, asnotifications/message, if the client wants the messages of the level, aslog_leveltells, 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 aprogress_token, and return whether it was sent.
- progress_token: Any¶
token = context.progress_token
The
progressTokenof the_metaof the request, which the notifications of its progress name, orNonefor 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/createMessageof the key, asinput()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 therole, thecontentand themodelof 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
requestStateof the resultinput_requiredgives 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
Nonefor 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 resultinput_requiredof its requests. A function lets it go, as anexcept Exceptionthat catches it would keep the server from asking.try: answer = context.elicit('confirm', 'Delete the file?') except InputRequired: raise except Exception: ...
- __weakref__¶
list of weak references to the object
- requests¶
requests = e.requests
The requests of the input, by their keys, as
inputRequestsgives them.
- class Pyjo.MCP.Server.Pyjo_MCP_Server(name: str = 'Pyjo.MCP', version: str = '1.0.0', instructions: str | None = None)[source]¶
Pyjo.MCP.Serverinherits all events and methods fromPyjo.EventEmitterand 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 theContextof the request. The action ofto_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.Serverobject.
- cache_scope¶
scope = server.cache_scope server.cache_scope = 'private'
Who may cache the results of
server/discoverandtools/list,publicby default, orprivatefor 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/discoverandtools/list, in milliseconds,0by 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.JSONdecodes it, or the JSON of one, and return aPyjo.Promiseof the response, or ofNonefor a notification, asdispatch_p()does. A batch, which MCP does not have, and a request with theidofnull, 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
heartbeatofPyjoyment, which keeps a connection without notifications from being closed by a proxy, in seconds,30by default, or0for never.
- instructions¶
instructions = server.instructions server.instructions = 'Arithmetic for the model.'
How a language model uses the server, which
server/discovergives, orNone.
- list_changed¶
boolean = server.list_changed server.list_changed = True
Whether
server/discoverdeclareslistChangedof the tools, the prompts and the resources, a promise that the application callsnotify_list_changed()when it changes a list, false by default.
- name¶
name = server.name server.name = 'calculator'
The name of the server,
Pyjo.MCPby 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 oftools,prompts,resourcesorresource_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/updatedof 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, asnotify_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.Promptof 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.Promptobjects of the server, in the order ofprompts/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.Resourceof the function with the options of its constructor, and return the function. A URI Template of RFC 6570 with variables adds a resource template, aPyjo.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.ResourceTemplateobjects of the server, in the order ofresources/templates/list, in whichresources/readtries them for a URI that no resource has.
- resources: list[Pyjo_MCP_Resource]¶
resources = server.resources
The
Pyjo.MCP.Resourceobjects of the server, in the order ofresources/list.
- secrets: list[str] | None¶
secrets = server.secrets server.secrets = ['passw0rd']
The secrets that sign the
requestStateof 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, orNonefor thesecretsof 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.Messagesobject, and return thePyjo.JSON.RPC.Clientof the peer, asserve()does, with the rules ofdispatch_p()and aContextof its own for each request, whoseclientis the one of the peer, whoseloggets the errors of the server, and whoseappis the application.notifications/cancelledof the peer cancels theContextof 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
requestStateof a request that needs input is valid,600by default, after which the client has to send the request again from its first round.
- subscribe¶
boolean = server.subscribe server.subscribe = True
Whether
server/discoverdeclaressubscribeof the resources, a promise that the application callsnotify_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 Acceptedwithout a body for a notification,405 Method Not Allowedfor another method of HTTP, and400 Bad Requestfor a header of MCP that does not match the body, asMCP-Protocol-Version,Mcp-Method,Mcp-NameandMcp-Param-{name}, or a request that is not valid. The first notification of the request, ofContext.notify(), turns the response into a stream of events,text/event-stream, where theAcceptof the request has it, with the notifications and then the response, with a comment everyheartbeatseconds, and a connection that closes before the result cancels theContext. A subscription ofsubscriptions/listenis such a stream, which needs theAcceptand 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_startof an application ofPyjoyment, the transport stdio, which serves the methods withserve()on the standard input and output ofPyjo.Server.Stdio, a message of JSON-RPC on each line, when the commandstdiostarts the application, and does nothing for another server, so that the same application serves Streamable HTTP withdaemon.# 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.Toolof 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.Toolobjects of the server, in the order oftools/list.
- version¶
version = server.version server.version = '2.0.0'
The version of the server,
1.0.0by default.