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

Pyjo.MCP.Server, Pyjo.MCP.Tool, Pyjo.UserAgent, Pyjo.MCP.

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.Client inherits all events and methods from Pyjo.EventEmitter and implements the following new ones.

Events

invalid_tool

@client.on('invalid_tool')
def invalid_tool(client, definition, e):
    ...

Emitted for a tool of tools/list with an x-mcp-header that the specification does not allow, which list_tools() leaves out, with the definition of the tool and the Pyjo.Exception of Pyjo.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.Client object, of Streamable HTTP, or of the transport stdio with a command.

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 id of the client, and the _meta that every request carries, over the _meta of the parameters.

build_tx(request: dict[str, Any]) → Pyjo_Transaction_HTTP[source]
tx = client.build_tx(request)

Build the Pyjo.Transaction.HTTP of a request or a notification, a POST to url with the headers of MCP made from the body, which reads a response in a stream of events too, as send_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.Error of the response. A result with isError is 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 resultType is input_required asks for input first, with the requests of its inputRequests, which the client answers, and the same call again with the responses, by the keys of the requests, as input_responses, and the requestState of the result as request_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 a Pyjo.Promise of the result instead of blocking.

capabilities: dict[str, Any]
capabilities = client.capabilities
client.capabilities = {'elicitation': {}}

The capabilities that every request declares, an empty dict by 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, wait shutdown_timeout seconds for it to exit, then send SIGTERM, and SIGKILL after as long again, and block until it has exited. The requests in progress fail. A client of Streamable HTTP closes the connections of its ua, unless the user agent was given to it. A with block 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 a Pyjo.Promise that is fulfilled once the server has exited, instead of blocking. An async with block 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 None for Streamable HTTP of url, 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 the Pyjo.JSON.RPC.Error of 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 a Pyjo.Promise of 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 a Pyjo.Promise of 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 empty dict by 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.Error of the response, with the input of the rounds of a request as call_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 a Pyjo.Promise of 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 Authorization of a server that requires a bearer token, an empty dict by 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 a Pyjo.Promise of 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 URIs read_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 a Pyjo.Promise of 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 a Pyjo.Promise of 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 in tools, which the calls take the headers of their arguments from. A tool whose x-mcp-header the specification does not allow is left out of the result and of tools, as the specification requires, with the event invalid_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 a Pyjo.Promise of 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, resourcesListChanged and resourceSubscriptions, and block until it ends. The function gets every message of the subscription, starting with notifications/subscriptions/acknowledged, whose notifications are the ones that the server sends, and closes the subscription when it returns False. Return the result of the response with which the server ends the subscription, or None for one that the function closed, or raise the Pyjo.JSON.RPC.Error of the response, or a Pyjo.Exception for 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 subscriptionId of its request, and the function closes it with notifications/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 a Pyjo.Promise of the result instead of blocking.

name
name = client.name
client.name = 'calculator-client'

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

property process: Pyjo_IOLoop_ChildProcess | None[source]
process = client.process

The Pyjo.IOLoop.ChildProcess of the server of command while it runs, or None.

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_VERSION by default. A server that rejects it with the error -32022 gets 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/read and return its result, or raise the Pyjo.JSON.RPC.Error of the response, as the one of a resource that does not exist, with the input of the rounds of a request as call_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 a Pyjo.Promise of 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, as send_request() does: from JSON or from a stream of events, and with the tools of a result of tools/list kept in tools, without the ones of the event invalid_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 None for a notification, which the server accepts without a response, 202 Accepted over Streamable HTTP. A response of HTTP without one of JSON-RPC fails with a Pyjo.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 of command that 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 a Pyjo.Promise of the response instead of blocking. The promise of this method, and the ones of the other methods with _p but listen_p(), abandon the request when they are cancelled with cancel(), as when the coroutine that awaits them is cancelled: the connection of Streamable HTTP closes, and the transport stdio sends notifications/cancelled, as the specification has it, and drops a response that comes after it. The promise is rejected with Request 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 of command to exit after the end of its standard input, and then after SIGTERM, before SIGKILL, in seconds, 5 by default.

tools: dict[str, Pyjo_MCP_Tool]
tools = client.tools

The Pyjo.MCP.Tool objects of the tools of the last list_tools(), by their names, whose x-mcp-header give the headers Mcp-Param-{name} of their calls.

property ua: Pyjo_UserAgent[source]
ua = client.ua
client.ua = Pyjo.UserAgent.new()

The Pyjo.UserAgent of 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/mcp by default.

version
version = client.version
client.version = '2.0.0'

The version of the client, 1.0.0 by default.