Other modules#
Module |
Contents |
|---|---|
Tasks that take several requests in the right order; see Operations. |
|
Build and walk Volto blocks; see Block helpers. |
|
The MCP server; needs the |
|
Authentication flows for httpx: basic, JWT, and a static token. |
|
Connection profiles and the configuration file. |
|
Secrets of profiles: keyring, environment variable, or command. |
|
UID references and |
MCP server#
An MCP server for Plone sites, built on the client and its operations.
The server gives chat assistants and agents without a shell the same access
the command line gives: the same profiles, secrets in the keyring, and the
same read_only and dry_run switches. It speaks over standard input
and output, or over streamable HTTP with a bearer token, for one site or
several:
pip install 'plone-client[mcp]'
plone-client mcp --profile blog
plone-client mcp --site blog --site docs
plone-client mcp --group customer
plone-client mcp --all
plone-client mcp --profile blog --http --port 8000
Rather than one tool per plone.restapi service, it offers the everyday
reads, the high-level operations of plone_client.operations, and one
tool for any other service. With several sites, every tool takes a site
argument, and list_sites describes them. Tools that change a site are
only offered when at least one site accepts changes; a change to a read-only
site is refused before it is sent. Each site also has read-only resources,
such as plone://blog/blocks, for users to attach to a conversation.
- plone_client.mcp_server.tool_errors(func)[source]#
Report the errors of a tool to the model, as JSON.
Unexpected exceptions reach the model only as “Error executing tool”, so the errors a caller can act on are turned into
ToolError.
- plone_client.mcp_server.resource_errors(func)[source]#
Report the errors of a resource to the client.
Unexpected exceptions reach the client only as a generic error, so a missing item becomes the “resource not found” of the protocol, and the errors a caller can act on keep their message.
- class plone_client.mcp_server.Site(name, url, description='', read_only=False, factory=None, client=None, blocks=<factory>, transitions=None, lock=<factory>)[source]#
Bases:
objectA site the server works on.
- Parameters:
name (str) – Name the model picks it by: the profile name.
url (str) – URL of the site.
description (str) – What the site is, for the model.
read_only (bool) – Whether changes to it are refused.
factory (Callable[[], PloneClient] | None) – Builds its client, on first use.
blocks (dict[str, Any]) – Block types that Markdown and HTML become on the site.
transitions (list[str] | None) – The only workflow transitions run on the site;
Nonefor all.lock (lock) – Held while a tool works on the site, one tool at a time: the client records the requests of an operation in one list, and block edits read and write the same item.
client (PloneClient | None)
- class plone_client.mcp_server.Sites(sites, *, dry_run=False)[source]#
Bases:
objectThe sites of one server, each with a client created on first use.
Creating a client looks up its secret, so a site whose secret is missing only fails when a tool uses it.
- Parameters:
- Raises:
ValueError – If there is no site, or two have the same name.
- classmethod from_client(client, name='site')[source]#
One site, served with a client that already exists.
- Parameters:
client (PloneClient) – The client.
name (str) – Name of the site.
- Returns:
The sites.
- Return type:
- classmethod from_profiles(profiles, *, read_only=False, dry_run=False, factory=<class 'plone_client.client.PloneClient'>)[source]#
Sites for profiles.
- Parameters:
- Returns:
The sites.
- Return type:
- site(name=None)[source]#
A site, by name.
- Parameters:
name (str | None) – Site name; the only site when there is one.
- Returns:
The site.
- Raises:
PloneConfigurationError – If the site is unknown.
- Return type:
- client(name=None)[source]#
The client of a site, created on first use.
- Parameters:
name (str | None) – Site name; the only site when there is one.
- Returns:
The client.
- Raises:
PloneConfigurationError – If the site is unknown, or its secret cannot be found.
- Return type:
- plone_client.mcp_server.rejected_sites(sites)[source]#
Names of the sites whose credentials the site rejects.
Connects to each site once, at startup. A site that cannot be reached, or whose secret cannot be found, is left out: its tools report that when used.
- plone_client.mcp_server.has_html2blocks()[source]#
Whether
collective.html2blocksis installed.- Returns:
Trueif it can be imported.- Return type:
- plone_client.mcp_server.build_server(target, rejected=(), tools=None)[source]#
An MCP server whose tools work on one site or several.
- Parameters:
target (PloneClient | Sites) – A client, for one site, or the sites. Each client’s
read_onlyanddry_runsettings apply to its tools.rejected (tuple[str, ...]) – Names of the sites whose credentials were rejected, for the instructions.
tools (Iterable[str] | None) – Names of the only tools to offer, to keep the list the model reads short; all when
None.list_sitesis offered with several sites either way. A resource is offered only when the tool that reads the same data is.
- Returns:
The server, ready to
run().- Raises:
PloneConfigurationError – If a tool in
toolsis not one this server offers, such as a tool that changes a read-only site.- Return type:
MCPServer
- class plone_client.mcp_server.HTTPSettings(token, host='127.0.0.1', port=8000, path='/mcp')[source]#
Bases:
objectHow the server listens over HTTP.
- class plone_client.mcp_server.BearerToken(app, token)[source]#
Bases:
objectASGI middleware that answers 401 to HTTP requests without the token.
The token is compared in constant time. Other ASGI scopes, such as the lifespan, pass through.
- Parameters:
- plone_client.mcp_server.http_app(server, settings)[source]#
The server as an ASGI application that requires the token.
- Parameters:
server (MCPServer) – The server, from
build_server().settings (HTTPSettings) – Where it listens, and its token.
- Returns:
The application.
- Return type:
Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]]
- plone_client.mcp_server.serve(target, tools=None, http=None)[source]#
Serve the tools over standard input and output, or over HTTP.
- Parameters:
target (PloneClient | Sites) – A client, for one site, or the sites; their clients are closed when the server stops.
tools (Iterable[str] | None) – Names of the only tools to offer; see
build_server().http (HTTPSettings | None) – Serve over streamable HTTP with these settings, instead of standard input and output.
- Raises:
PloneConfigurationError – If a tool in
toolsis not offered.- Return type:
None
Authentication#
Authentication strategies for PloneClient.
Three ways to authenticate against plone.restapi are supported:
HTTP basic authentication (
httpx.BasicAuth), the simplest option and the default when a username and password are given;a JWT obtained from
@login(JWTAuth), which logs in again when the token expires;a token issued beforehand (
TokenAuth).
Any other httpx.Auth can be passed to the client as well.
- class plone_client.auth.TokenAuth(token)[source]#
Bases:
AuthSend a token issued beforehand as
Authorization: Bearer.- Parameters:
token (str) – The JWT.
- auth_flow(request)[source]#
Execute the authentication flow.
To dispatch a request, yield it:
` yield request `The client will .send() the response back into the flow generator. You can access it like so:
` response = yield request `A return (or reaching the end of the generator) will result in the client returning the last response obtained from the server.
You can dispatch as many requests as is necessary.
- Parameters:
request (Request)
- Return type:
Generator[Request, Response, None]
- class plone_client.auth.JWTAuth(username, password, login_url)[source]#
Bases:
AuthLog in with
POST @loginand send the JWT it returns.The login happens on the first request. When the site answers
401, the token is assumed to be expired: the flow logs in again and repeats the request once.- Parameters:
- auth_flow(request)[source]#
Execute the authentication flow.
To dispatch a request, yield it:
` yield request `The client will .send() the response back into the flow generator. You can access it like so:
` response = yield request `A return (or reaching the end of the generator) will result in the client returning the last response obtained from the server.
You can dispatch as many requests as is necessary.
- Parameters:
request (Request)
- Return type:
Generator[Request, Response, None]
- plone_client.auth.build_auth(*, username='', password='', token='', method='basic', login_url='')[source]#
Pick the authentication for a set of credentials.
A token wins over a username and password. Without any credential the client is anonymous.
- Parameters:
- Returns:
The authentication, or
Nonefor anonymous access.- Raises:
ValueError – If the method is unknown or only half of the username/password pair is given.
- Return type:
Auth | None
Profiles#
Named connection profiles, so one machine can talk to many sites.
A profile names a site, a user and where that user’s secret is kept. The
profiles live in a TOML file, by default ~/.config/plone-client/config.toml
($XDG_CONFIG_HOME and $PLONE_CLIENT_CONFIG are honored):
current = "blog"
[defaults]
timeout = 60
retries = 5
[profiles.blog]
url = "https://example.org"
username = "editor"
[profiles.local]
url = "http://localhost:8080/Plone"
username = "admin"
auth = "jwt"
[profiles.production]
url = "https://www.example.com"
username = "editor"
read_only = true
secret = "command"
secret_command = "op read op://Private/example/password"
verify = "/etc/ssl/certs/example-ca.pem"
[groups]
sites = ["blog", "production"]
The defaults table holds the connection settings shared by every
profile (see DEFAULT_KEYS); a profile’s own value wins. The
groups table names lists of profiles, which the MCP server can serve
together (plone-client mcp --group sites).
Secrets never go in the file. By default they are kept in the operating
system’s keyring (macOS Keychain, Windows Credential Locker, Secret Service
on Linux); see plone_client.credentials for the other sources.
Which profile is used, from the strongest choice to the weakest: the name
passed explicitly, $PLONE_CLIENT_PROFILE, a .plone-client.toml file
in the working directory or one of its parents (profile = "blog"), and
the current profile of the configuration file.
- plone_client.profiles.DEFAULT_KEYS: tuple[str, ...] = ('timeout', 'verify', 'retries', 'backoff', 'api_prefix', 'read_only')#
Settings allowed in the
defaultstable of the configuration file.
- plone_client.profiles.parse_verify(value)[source]#
Read a
verifysetting written as text.- Parameters:
value (str) –
trueorfalse(also1/0,yes/no,on/off), or the path of a CA bundle.- Returns:
A boolean, or the path.
- Raises:
PloneConfigurationError – If the value is empty.
- Return type:
- plone_client.profiles.default_config_path(environ=None)[source]#
Path of the user’s configuration file.
- plone_client.profiles.find_project_profile(start=None)[source]#
Profile named by a
.plone-client.tomlfile.The file is looked for in
startand in each of its parents, so a repository can say which site it works with. It holds no secrets and can be committed.
- class plone_client.profiles.Profile(name, url, username='', auth='basic', secret='keyring', secret_env='PLONE_CLIENT_PASSWORD', secret_command='', read_only=False, transitions=<factory>, timeout=30.0, verify=True, retries=3, backoff=0.5, api_prefix='++api++', frontend_url='', blocks=<factory>, description='')[source]#
Bases:
objectConnection settings of one site.
- Parameters:
name (str) – Profile name.
url (str) – URL of the site root.
username (str) – Login name; empty for anonymous access.
auth (Literal['basic', 'jwt', 'token']) –
basicorjwtwith a username and password, ortokento send the secret as a JWT.secret (Literal['keyring', 'env', 'command', 'none']) – Where the secret is kept:
keyring,env,commandornone.secret_env (str) – Variable holding the secret, with
secret = "env".secret_command (str) – Command printing the secret, with
secret = "command"; run without a shell.read_only (bool) – Refuse every request that could change the site.
transitions (list[str]) – The only workflow transitions run on this site, such as
["submit"]; empty for all of them.timeout (float) – Seconds to wait for the site.
verify (bool | str) – Verify TLS certificates; a path verifies them against that CA bundle (a file or a directory) instead of the default one.
retries (int) – Times a request is repeated after a network error or an overloaded site; see
PloneClient.backoff (float) – Base delay in seconds between retries.
api_prefix (str) – Traversal prefix of the REST API.
frontend_url (str) – URL of the Volto frontend, when
urlis the backend; used for services that Volto serves (@blocks-schema).blocks (dict[str, Any]) – Block types that Markdown and HTML become on this site, such as
{"codeBlock": True}; seeplone_client.blocks.BlocksSetting.description (str) – Free text, shown by
plone-client profile list.
- classmethod from_mapping(name, data)[source]#
Build a profile from a table of the configuration file.
- get_secret()[source]#
The profile’s password or token.
- Returns:
The secret, or an empty string for anonymous profiles.
- Raises:
PloneConfigurationError – If the secret cannot be found.
- Return type:
- client_settings()[source]#
Keyword arguments for
PloneClient.
- class plone_client.profiles.Config(path, data=None)[source]#
Bases:
objectThe profiles of a configuration file.
- group(name)[source]#
The profiles of a group.
- Parameters:
name (str) – Group name.
- Returns:
The profiles, in the group’s order.
- Raises:
PloneConfigurationError – If there is no such group.
- Return type:
- remove_group(name)[source]#
Remove a group; its profiles are kept.
- Parameters:
name (str) – Group name.
- Returns:
The members it had.
- Raises:
PloneConfigurationError – If there is no such group.
- Return type:
- set_defaults(values)[source]#
Change the settings shared by every profile.
Profiles that took a setting from the old defaults take it from the new ones; settings of their own are kept.
- Parameters:
values (Mapping[str, Any]) – Settings to set;
Noneremoves a setting.- Raises:
PloneConfigurationError – If a key is not one of
DEFAULT_KEYSor a value is invalid.- Return type:
None
- get(name)[source]#
A profile by name.
- Parameters:
name (str) – Profile name.
- Returns:
The profile.
- Raises:
PloneConfigurationError – If there is no such profile.
- Return type:
- current_name(environ=None, cwd=None)[source]#
Name of the profile to use when none is given explicitly.
- add(profile, *, replace=False)[source]#
Add a profile.
- Parameters:
- Raises:
PloneConfigurationError – If the name is taken.
- Return type:
None
- save()[source]#
Write the configuration file, readable only by its owner.
- Raises:
PloneConfigurationError – If
tomlkitis not installed.- Return type:
None
- plone_client.profiles.load_config(path=None)[source]#
Read a configuration file.
- Parameters:
path (Path | None) – Path of the file; the user’s by default. A missing file gives an empty configuration.
- Returns:
The configuration.
- Raises:
PloneConfigurationError – If the file is not valid.
- Return type:
- plone_client.profiles.settings_from_env(environ, *, prefix='PLONE_CLIENT_')[source]#
Client settings from environment variables.
Reads
URL,USERNAME(orUSER),PASSWORD,TOKEN,AUTH_METHOD,API_PREFIX,TIMEOUT,VERIFY(true,falseor a CA bundle path),RETRIES,BACKOFF,READ_ONLY,TRANSITIONS(ids separated by commas),FRONTEND_URLandBLOCKS(a JSON object), each after the prefix. Withprefix="REMOTE_", this reads theREMOTE_URL,REMOTE_USERandREMOTE_PASSWORDvariables used by older scripts.- Parameters:
- Returns:
Keyword arguments for
PloneClient.- Raises:
PloneConfigurationError – If the URL is not set.
- Return type:
Credentials#
Where the password or token of a profile is kept.
keyring(default)The operating system’s secret store, through the
keyringpackage: macOS Keychain, Windows Credential Locker, or the Secret Service on Linux. Entries are stored under the serviceplone-client:<profile>.envAn environment variable, named by the profile’s
secret_env(PLONE_CLIENT_PASSWORDby default). Handy in CI.commandThe output of a command, named by the profile’s
secret_command, such asop read op://Private/site/passwordorpass show plone/site. The command runs without a shell.noneNo secret: the profile is anonymous.
The token that MCP clients send to plone-client mcp --http is kept in the
keyring too, under the service plone-client (no profile has that
service), or in $PLONE_CLIENT_MCP_TOKEN, which wins.
- plone_client.credentials.get_secret(profile)[source]#
Look up the secret of a profile.
- Parameters:
profile (Profile) – The profile.
- Returns:
The password or token.
- Raises:
PloneConfigurationError – If the secret is missing.
- Return type:
- plone_client.credentials.set_secret(profile, value)[source]#
Store the secret of a profile in the keyring.
- Parameters:
- Raises:
PloneConfigurationError – If the profile keeps its secret elsewhere.
- Return type:
None
- plone_client.credentials.delete_secret(profile)[source]#
Remove the secret of a profile from the keyring.
- plone_client.credentials.MCP_TOKEN_ENV = 'PLONE_CLIENT_MCP_TOKEN'#
Environment variable with the token of the MCP server; wins over the keyring.
- plone_client.credentials.MCP_TOKEN_ACCOUNT = 'mcp-token'#
Keyring account of the MCP server’s token, under the service
plone-client.
- plone_client.credentials.MCP_TOKEN_MIN_LENGTH = 32#
Shortest token the MCP server accepts.
- plone_client.credentials.get_mcp_token()[source]#
The token that MCP clients must send to the HTTP server.
- Returns:
$PLONE_CLIENT_MCP_TOKENwhen set, or the token in the keyring.- Raises:
PloneConfigurationError – If there is none, or it is too short.
- Return type:
- plone_client.credentials.set_mcp_token(value)[source]#
Store the token of the MCP server in the keyring.
- Parameters:
value (str) – The token.
- Raises:
PloneConfigurationError – If it is too short.
- Return type:
None
Utilities#
Small helpers shared by the library and the command line.
- plone_client.utils.UID_RE = re.compile('^[0-9a-f]{32}$')#
A Plone UID: 32 lowercase hexadecimal characters.