Pyjo.MCP.Client - Client of MCP¶
from Pyjo.MCP.Client import Client
client = Client('http://127.0.0.1:3000/mcp')
tools = client.list_tools()['tools']
# Or import the module, as in Google Python Style Guide
import Pyjo.MCP.Client
client = Pyjo.MCP.Client.new('http://127.0.0.1:3000/mcp', name='calculator-client')
result = client.call_tool('add', {'a': 1, 'b': 2})
print(result['structuredContent'])
# Non-blocking
client.call_tool_p('add', {'a': 1, 'b': 2}).then(lambda result: print(result['structuredContent'])).wait()
# The transport stdio, of a server in a child process
with Pyjo.MCP.Client.new(command=['python', 'calculator.py', 'stdio']) as client:
print(client.call_tool('add', {'a': 1, 'b': 2})['structuredContent'])
Pyjo.MCP.Client is a client of the Model Context Protocol over
Streamable HTTP, of the revision Pyjo.MCP.PROTOCOL_VERSION of the
specification, made with Pyjo.UserAgent. It sends what every request
carries, the _meta with the revision, the capabilities and the name of the
client, and the headers of MCP made from the body, MCP-Protocol-Version,
Mcp-Method, Mcp-Name and the Mcp-Param-{name} of the
x-mcp-header of a tool, and reads the response in JSON or in a stream of
events.
With a command, it speaks the transport stdio
instead: it runs the server in a child process of
Pyjo.IOLoop.ChildProcess at its first request, and sends the messages
to its standard input and reads them from its standard output, one on each
line, with Pyjo.IOLoop.Messages. The methods are the same for both
transports.
It is a client to test a server with and to start from, not an agent: it
caches nothing for the ttlMs of a result, and leaves the authorization to
the application, which sends its headers with headers.
See also¶
Classes¶
- class Pyjo.MCP.Client.Pyjo_MCP_Client(url: str = 'http://localhost:3000/mcp', ua: Pyjo_UserAgent | None = None, name: str = 'Pyjo.MCP', version: str = '1.0.0', *, command: Sequence[str] | None = None, cwd: str | PathLike[str] | None = None, env: Mapping[str, str] | None = None)[source]¶
Pyjo.MCP.Clientinherits all events and methods fromPyjo.EventEmitterand implements the following new ones.Events¶
invalid_tool@client.on('invalid_tool') def invalid_tool(client, definition, e): ...
Emitted for a tool of
tools/listwith anx-mcp-headerthat the specification does not allow, whichlist_tools()leaves out, with the definition of the tool and thePyjo.ExceptionofPyjo.MCP.Tool.client.on('invalid_tool', lambda client, definition, e: print(f'{definition["name"]}: {e.message}'))
notification@client.on('notification') def notification(client, message): ...
Emitted for every message of the stream of events of a response that is not the response itself, as a notification of the progress of a tool, or, over the transport stdio, for every notification of the server that is not a message of a subscription of
listen().client.on('notification', lambda client, message: print(message['method']))
stderr@client.on('stderr') def stderr(client, chunk): ...
Emitted for the standard error of the server of the transport stdio, as
bytes, which goes to the standard error of this process without a subscriber. The specification lets a server log there, so it is not an error of the server.client.on('stderr', lambda client, chunk: log.debug(chunk.decode(errors='replace')))
- __init__(url: str = 'http://localhost:3000/mcp', ua: Pyjo_UserAgent | None = None, name: str = 'Pyjo.MCP', version: str = '1.0.0', *, command: Sequence[str] | None = None, cwd: str | PathLike[str] | None = None, env: Mapping[str, str] | None = None) None[source]¶
client = Pyjo.MCP.Client.new() client = Pyjo.MCP.Client.new('http://127.0.0.1:3000/mcp', name='calculator-client', version='2.0.0') client = Pyjo.MCP.Client.new('/mcp', ua=t.ua) client = Pyjo.MCP.Client.new(command=['uv', 'run', 'app.py', 'stdio'], cwd='/srv/app', env={'DEBUG': '1'})
Construct a new
Pyjo.MCP.Clientobject, of Streamable HTTP, or of the transport stdio with acommand.
- build_notification(method: str, params: dict[str, Any] | None = None) dict[str, Any][source]¶
notification = client.build_notification('notifications/cancelled', {'requestId': 1})
Build a notification of JSON-RPC with the method and its parameters.
- build_request(method: str, params: dict[str, Any] | None = None) dict[str, Any][source]¶
request = client.build_request('tools/call', {'name': 'add', 'arguments': {'a': 1, 'b': 2}})
Build a request of JSON-RPC with the method and its parameters, the next
idof the client, and the_metathat every request carries, over the_metaof the parameters.
- build_tx(request: dict[str, Any]) Pyjo_Transaction_HTTP[source]¶
tx = client.build_tx(request)
Build the
Pyjo.Transaction.HTTPof a request or a notification, a POST tourlwith the headers of MCP made from the body, which reads a response in a stream of events too, assend_request()does, so that a test sends what the client sends.# The request without its header Mcp-Name tx = client.build_tx(client.build_request('tools/call', {'name': 'add', 'arguments': {}})) tx.req.headers.remove('Mcp-Name') t.request_ok(tx).status_is(400)
- call_tool(name: str, arguments: dict[str, Any] | None = None, /, *, input_responses: dict[str, Any] | None = None, request_state: str | None = None) dict[str, Any][source]¶
result = client.call_tool('greet') result = client.call_tool('greet', {'name': 'Pyjo'}) result = client.call_tool('delete', {'path': 'a.txt'}, input_responses=responses, request_state=state)
Call a tool with its arguments and return its result, or raise the
Pyjo.JSON.RPC.Errorof the response. A result withisErroris a result, of an error of the execution of the tool.result = client.call_tool('divide', {'a': 1, 'b': 0}) if result['isError']: print(result['content'][0]['text'])
A result whose
resultTypeisinput_requiredasks for input first, with the requests of itsinputRequests, which the client answers, and the same call again with the responses, by the keys of the requests, asinput_responses, and therequestStateof the result asrequest_state, is the next round of the request.result = client.call_tool('delete', {'path': 'a.txt'}) while result['resultType'] == 'input_required': responses = {key: {'action': 'accept'} for key in result['inputRequests']} state = result.get('requestState') result = client.call_tool('delete', {'path': 'a.txt'}, input_responses=responses, request_state=state)
- call_tool_p(name: str, arguments: dict[str, Any] | None = None, /, *, input_responses: dict[str, Any] | None = None, request_state: str | None = None) Pyjo_Promise[source]¶
promise = client.call_tool_p('greet', {'name': 'Pyjo'})
Same as
call_tool(), but returns aPyjo.Promiseof the result instead of blocking.
- capabilities: dict[str, Any]¶
capabilities = client.capabilities client.capabilities = {'elicitation': {}}
The capabilities that every request declares, an empty
dictby default.
- close() None[source]¶
client.close()
End the server of
command, as the specification asks of a client of the transport stdio: close its standard input, waitshutdown_timeoutseconds for it to exit, then sendSIGTERM, andSIGKILLafter as long again, and block until it has exited. The requests in progress fail. A client of Streamable HTTP closes the connections of itsua, unless the user agent was given to it. Awithblock closes the client at its end.with Pyjo.MCP.Client.new(command=['python', 'calculator.py', 'stdio']) as client: print(client.list_tools()['tools'])
- close_p() Pyjo_Promise[source]¶
promise = client.close_p()
Same as
close(), but returns aPyjo.Promisethat is fulfilled once the server has exited, instead of blocking. Anasync withblock closes the client with it.async with Pyjo.MCP.Client.new(command=['python', 'calculator.py', 'stdio']) as client: print((await client.list_tools_p())['tools'])
- command: list[str] | None¶
command = client.command client.command = ['uv', 'run', 'app.py', 'stdio']
The program and the arguments of the server of the transport stdio, which the client runs in a child process at its first request, and again at the first request after the process has exited, or
Nonefor Streamable HTTP ofurl, the default.
- complete(ref: dict[str, Any], argument: str, value: str, arguments: dict[str, str] | None = None) dict[str, Any][source]¶
result = client.complete({'type': 'ref/prompt', 'name': 'review'}, 'language', 'Py') result = client.complete({'type': 'ref/resource', 'uri': 'repo://{owner}/{repo}'}, 'repo', 'Py', {'owner': 'dex4er'})
Complete the value of an argument of a prompt, or of a variable of a resource template, with
completion/complete, with the values of the other arguments, and return its result, or raise thePyjo.JSON.RPC.Errorof the response.print(client.complete({'type': 'ref/prompt', 'name': 'review'}, 'language', 'P')['completion']['values'])
- complete_p(ref: dict[str, Any], argument: str, value: str, arguments: dict[str, str] | None = None) Pyjo_Promise[source]¶
promise = client.complete_p({'type': 'ref/prompt', 'name': 'review'}, 'language', 'Py')
Same as
complete(), but returns aPyjo.Promiseof the result instead of blocking.
- cwd¶
cwd = client.cwd client.cwd = '/srv/app'
The working directory of the server of
command, the one of this process by default.
- discover() dict[str, Any][source]¶
result = client.discover()
Discover the revisions, the capabilities and the instructions of the server with
server/discover.
- discover_p() Pyjo_Promise[source]¶
promise = client.discover_p()
Same as
discover(), but returns aPyjo.Promiseof the result instead of blocking.
- env: dict[str, str]¶
env = client.env client.env = {'DEBUG': '1'}
The variables of the environment of the server of
command, over the ones of this process, an emptydictby default.
- get_prompt(name: str, arguments: dict[str, Any] | None = None, /, *, input_responses: dict[str, Any] | None = None, request_state: str | None = None) dict[str, Any][source]¶
result = client.get_prompt('summary') result = client.get_prompt('review', {'code': 'x = 1'}) result = client.get_prompt('review', {'code': 'x = 1'}, input_responses=responses, request_state=state)
Get the messages of a prompt with its arguments, whose values are strings, and return its result, or raise the
Pyjo.JSON.RPC.Errorof the response, with the input of the rounds of a request ascall_tool()has it.for message in client.get_prompt('review', {'code': 'x = 1'})['messages']: print(message['role'], message['content'].get('text'))
- get_prompt_p(name: str, arguments: dict[str, Any] | None = None, /, *, input_responses: dict[str, Any] | None = None, request_state: str | None = None) Pyjo_Promise[source]¶
promise = client.get_prompt_p('review', {'code': 'x = 1'})
Same as
get_prompt(), but returns aPyjo.Promiseof the result instead of blocking.
- headers: dict[str, Any]¶
headers = client.headers client.headers = {'Authorization': 'Bearer abc123'}
The headers of HTTP of every request, as the
Authorizationof a server that requires a bearer token, an emptydictby default.
- list_prompts() dict[str, Any][source]¶
result = client.list_prompts()
List the prompts of the server with
prompts/list.for prompt in client.list_prompts()['prompts']: print(prompt['name'], [argument['name'] for argument in prompt.get('arguments', [])])
- list_prompts_p() Pyjo_Promise[source]¶
promise = client.list_prompts_p()
Same as
list_prompts(), but returns aPyjo.Promiseof the result instead of blocking.
- list_resource_templates() dict[str, Any][source]¶
result = client.list_resource_templates()
List the resource templates of the server with
resources/templates/list, whose URIsread_resource()reads.for template in client.list_resource_templates()['resourceTemplates']: print(template['uriTemplate'], template.get('mimeType'))
- list_resource_templates_p() Pyjo_Promise[source]¶
promise = client.list_resource_templates_p()
Same as
list_resource_templates(), but returns aPyjo.Promiseof the result instead of blocking.
- list_resources() dict[str, Any][source]¶
result = client.list_resources()
List the resources of the server with
resources/list.for resource in client.list_resources()['resources']: print(resource['uri'], resource.get('mimeType'))
- list_resources_p() Pyjo_Promise[source]¶
promise = client.list_resources_p()
Same as
list_resources(), but returns aPyjo.Promiseof the result instead of blocking.
- list_tools() dict[str, Any][source]¶
result = client.list_tools()
List the tools of the server with
tools/list, and keep them intools, which the calls take the headers of their arguments from. A tool whosex-mcp-headerthe specification does not allow is left out of the result and oftools, as the specification requires, with the eventinvalid_tool.for tool in client.list_tools()['tools']: print(tool['name'], tool.get('description'))
- list_tools_p() Pyjo_Promise[source]¶
promise = client.list_tools_p()
Same as
list_tools(), but returns aPyjo.Promiseof the result instead of blocking.
- listen(notifications: dict[str, Any], cb: Callable[[dict[str, Any]], Any]) dict[str, Any] | None[source]¶
result = client.listen({'toolsListChanged': True}, lambda message: print(message['method'])) result = client.listen({'resourceSubscriptions': ['file:///project/README.md']}, cb)
Open a subscription with
subscriptions/listen, for the notifications that the filter asks for,toolsListChanged,promptsListChanged,resourcesListChangedandresourceSubscriptions, and block until it ends. The function gets every message of the subscription, starting withnotifications/subscriptions/acknowledged, whosenotificationsare the ones that the server sends, and closes the subscription when it returnsFalse. Return the result of the response with which the server ends the subscription, orNonefor one that the function closed, or raise thePyjo.JSON.RPC.Errorof the response, or aPyjo.Exceptionfor a connection that closes without one.# Until the third change of the resource def updated(message): if message['method'] == 'notifications/resources/updated': updated.count += 1 print(f'Changed: {message["params"]["uri"]}') return updated.count < 3 updated.count = 0 client.listen({'resourceSubscriptions': ['file:///project/README.md']}, updated) print(client.read_resource('file:///project/README.md')['contents'][0]['text'])
Over the transport stdio, the messages of the subscription are those of the
subscriptionIdof its request, and the function closes it withnotifications/cancelled.
- listen_p(notifications: dict[str, Any], cb: Callable[[dict[str, Any]], Any]) Pyjo_Promise[source]¶
promise = client.listen_p({'toolsListChanged': True}, lambda message: print(message['method']))
Same as
listen(), but returns aPyjo.Promiseof the result instead of blocking.
- name¶
name = client.name client.name = 'calculator-client'
The name of the client,
Pyjo.MCPby default.
- property process: Pyjo_IOLoop_ChildProcess | None[source]¶
process = client.process
The
Pyjo.IOLoop.ChildProcessof the server ofcommandwhile it runs, orNone.print(client.process.pid)
- protocol_version¶
version = client.protocol_version client.protocol_version = '2026-07-28'
The revision of the specification of the requests,
Pyjo.MCP.PROTOCOL_VERSIONby default. A server that rejects it with the error-32022gets the request once more, of the newest revision that both support, which the client keeps for the next requests.
- read_resource(uri: str, *, input_responses: dict[str, Any] | None = None, request_state: str | None = None) dict[str, Any][source]¶
result = client.read_resource('file:///project/README.md') result = client.read_resource('file:///project/README.md', input_responses=responses, request_state=state)
Read the contents of a resource with
resources/readand return its result, or raise thePyjo.JSON.RPC.Errorof the response, as the one of a resource that does not exist, with the input of the rounds of a request ascall_tool()has it.for contents in client.read_resource('file:///project/README.md')['contents']: print(contents.get('text'))
- read_resource_p(uri: str, *, input_responses: dict[str, Any] | None = None, request_state: str | None = None) Pyjo_Promise[source]¶
promise = client.read_resource_p('file:///project/README.md')
Same as
read_resource(), but returns aPyjo.Promiseof the result instead of blocking.
- read_response(tx: Pyjo_Transaction_HTTP, request: dict[str, Any]) dict[str, Any] | None[source]¶
response = client.read_response(tx, request)
Read the response of a request from its transaction of
build_tx(), once the transaction is done, assend_request()does: from JSON or from a stream of events, and with the tools of a result oftools/listkept intools, without the ones of the eventinvalid_tool.request = client.build_request('tools/list') tx = client.ua.start(client.build_tx(request)) print(client.read_response(tx, request)['result']['tools'])
- send_request(request: dict[str, Any]) dict[str, Any] | None[source]¶
response = client.send_request(request)
Send a request or a notification and return the response, or
Nonefor a notification, which the server accepts without a response,202 Acceptedover Streamable HTTP. A response of HTTP without one of JSON-RPC fails with aPyjo.Exception, with the text of an error in plain text, as a server of an older revision tells the revisions that it supports, and so does a server ofcommandthat cannot run or exits before the response.response = client.send_request(client.build_request('tools/list')) print(response['result']['tools'])
Over the transport stdio, the blocking methods wait for their responses with the event loop, so they cannot be called in an event loop that runs already, where the methods with a promise can.
- send_request_p(request: dict[str, Any]) Pyjo_Promise[source]¶
promise = client.send_request_p(request)
Same as
send_request(), but returns aPyjo.Promiseof the response instead of blocking. The promise of this method, and the ones of the other methods with_pbutlisten_p(), abandon the request when they are cancelled withcancel(), as when the coroutine that awaits them is cancelled: the connection of Streamable HTTP closes, and the transport stdio sendsnotifications/cancelled, as the specification has it, and drops a response that comes after it. The promise is rejected withRequest cancelled.promise = client.call_tool_p('count', {'to': 100}) Pyjo.IOLoop.timer(1, lambda loop: promise.cancel())
- shutdown_timeout: float¶
timeout = client.shutdown_timeout client.shutdown_timeout = 1
How long
close()waits for the server ofcommandto exit after the end of its standard input, and then afterSIGTERM, beforeSIGKILL, in seconds,5by default.
- tools: dict[str, Pyjo_MCP_Tool]¶
tools = client.tools
The
Pyjo.MCP.Toolobjects of the tools of the lastlist_tools(), by their names, whosex-mcp-headergive the headersMcp-Param-{name}of their calls.
- property ua: Pyjo_UserAgent[source]¶
ua = client.ua client.ua = Pyjo.UserAgent.new()
The
Pyjo.UserAgentof the requests, a new one by default.
- url¶
url = client.url client.url = 'http://127.0.0.1:3000/mcp'
The URL of the endpoint of MCP,
http://localhost:3000/mcpby default.
- version¶
version = client.version client.version = '2.0.0'
The version of the client,
1.0.0by default.