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()
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.
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')[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.
client.on('notification', lambda client, message: print(message['method']))
- __init__(url: str = 'http://localhost:3000/mcp', ua: Pyjo_UserAgent | None = None, name: str = 'Pyjo.MCP', version: str = '1.0.0') 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)
Construct a new
Pyjo.MCP.Clientobject.
- 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.
- 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.
- 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.
- 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'])
- 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.
- 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 one that the server accepted without a response,202 Accepted. 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.response = client.send_request(client.build_request('tools/list')) print(response['result']['tools'])
- 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.
- 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.