Other modules#

Module

Contents

plone_client.operations

Tasks that take several requests in the right order; see Operations.

plone_client.blocks

Build and walk Volto blocks; see Block helpers.

plone_client.mcp_server

The MCP server; needs the mcp extra.

plone_client.auth

Authentication flows for httpx: basic, JWT, and a static token.

plone_client.profiles

Connection profiles and the configuration file.

plone_client.credentials

Secrets of profiles: keyring, environment variable, or command.

plone_client.utils

UID references and resolveuid links.

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.

Parameters:

func (Callable[[...], Any]) – The tool.

Returns:

The wrapped tool.

Return type:

Callable[[…], Any]

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.

Parameters:

func (Callable[[...], Any]) – The resource function.

Returns:

The wrapped function.

Return type:

Callable[[…], Any]

class plone_client.mcp_server.Site(name, url, description='', read_only=False, factory=None, client=None, blocks=<factory>, transitions=None, lock=<factory>)[source]#

Bases: object

A 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; None for 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)

summary()[source]#

The site, as list_sites reports it.

Returns:

name, url, description, read_only and blocks, and transitions when only some run.

Return type:

dict[str, Any]

class plone_client.mcp_server.Sites(sites, *, dry_run=False)[source]#

Bases: object

The 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:
  • sites (Iterable[Site]) – The sites, in the order the model sees them.

  • dry_run (bool) – Whether the clients skip the requests that change a site.

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:

Sites

classmethod from_profiles(profiles, *, read_only=False, dry_run=False, factory=<class 'plone_client.client.PloneClient'>)[source]#

Sites for profiles.

Parameters:
  • profiles (Iterable[Profile]) – The profiles.

  • read_only (bool) – Refuse changes to every site, whatever its profile.

  • dry_run (bool) – Skip the requests that change a site.

  • factory (Callable[[...], PloneClient]) – Builds a client from keyword arguments.

Returns:

The sites.

Return type:

Sites

property names: list[str]#

Names of the sites, in order.

property multiple: bool#

Whether there is more than one site.

property writable: bool#

Whether at least one site accepts changes.

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:

Site

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:

PloneClient

close()[source]#

Close the clients that were created.

Return type:

None

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.

Parameters:

sites (Sites) – The sites.

Returns:

Names of the sites, in order.

Return type:

list[str]

plone_client.mcp_server.has_html2blocks()[source]#

Whether collective.html2blocks is installed.

Returns:

True if it can be imported.

Return type:

bool

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_only and dry_run settings 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_sites is 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 tools is 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: object

How the server listens over HTTP.

Parameters:
  • token (str) – Token that clients send as Authorization: Bearer.

  • host (str) – Address to listen on. Other hosts than the loopback should be reached through a proxy that adds TLS.

  • port (int) – Port to listen on.

  • path (str) – Path of the MCP endpoint.

class plone_client.mcp_server.BearerToken(app, token)[source]#

Bases: object

ASGI 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:
authorized(scope)[source]#

Whether a request carries the token.

Parameters:

scope (MutableMapping[str, Any]) – The ASGI scope of the request.

Returns:

True for Authorization: Bearer <token>.

Return type:

bool

plone_client.mcp_server.http_app(server, settings)[source]#

The server as an ASGI application that requires the token.

Parameters:
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 tools is 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: Auth

Send 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: Auth

Log in with POST @login and 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:
  • username (str) – Login name.

  • password (str) – Password.

  • login_url (str) – Absolute URL of the site’s @login service.

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:
  • username (str) – Login name.

  • password (str) – Password.

  • token (str) – JWT issued beforehand.

  • method (Literal['basic', 'jwt']) – basic or jwt, used with a username and password.

  • login_url (str) – Absolute URL of @login, needed by jwt.

Returns:

The authentication, or None for 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 defaults table of the configuration file.

plone_client.profiles.parse_verify(value)[source]#

Read a verify setting written as text.

Parameters:

value (str) – true or false (also 1/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:

bool | str

plone_client.profiles.default_config_path(environ=None)[source]#

Path of the user’s configuration file.

Parameters:

environ (Mapping[str, str] | None) – Environment; os.environ by default.

Returns:

$PLONE_CLIENT_CONFIG, or config.toml inside $XDG_CONFIG_HOME/plone-client (~/.config/plone-client).

Return type:

Path

plone_client.profiles.find_project_profile(start=None)[source]#

Profile named by a .plone-client.toml file.

The file is looked for in start and in each of its parents, so a repository can say which site it works with. It holds no secrets and can be committed.

Parameters:

start (Path | None) – Directory to start from; the working directory by default.

Returns:

The profile name, or an empty string when there is no file.

Return type:

str

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: object

Connection 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']) – basic or jwt with a username and password, or token to send the secret as a JWT.

  • secret (Literal['keyring', 'env', 'command', 'none']) – Where the secret is kept: keyring, env, command or none.

  • 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 url is 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}; see plone_client.blocks.BlocksSetting.

  • description (str) – Free text, shown by plone-client profile list.

property anonymous: bool#

Whether requests go out without credentials.

classmethod from_mapping(name, data)[source]#

Build a profile from a table of the configuration file.

Parameters:
Returns:

The profile.

Raises:

PloneConfigurationError – If a key is unknown or a value invalid.

Return type:

Profile

to_mapping(defaults=None)[source]#

Table for the configuration file, without default values.

Parameters:

defaults (Mapping[str, Any] | None) – The defaults table; values equal to it are left out, so the profile keeps following it.

Returns:

The settings that differ from the defaults, url first.

Return type:

dict[str, Any]

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:

str

client_settings()[source]#

Keyword arguments for PloneClient.

Returns:

URL, credentials and options; the secret is looked up now.

Return type:

dict[str, Any]

summary()[source]#

Description of the profile, safe to print.

Returns:

Settings without any secret.

Return type:

dict[str, Any]

class plone_client.profiles.Config(path, data=None)[source]#

Bases: object

The profiles of a configuration file.

Parameters:
  • path (Path) – Path of the file.

  • data (Mapping[str, Any] | None) – Parsed contents.

groups: dict[str, list[str]]#

Named lists of profiles, such as the sites of one customer.

set_group(name, members)[source]#

Create or replace a group of profiles.

Parameters:
  • name (str) – Group name.

  • members (Iterable[str]) – Names of the profiles in the group; duplicates are dropped and the order kept.

Returns:

The members.

Raises:

PloneConfigurationError – If the name is invalid, the group is empty, or a profile does not exist.

Return type:

list[str]

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:

list[Profile]

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:

list[str]

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; None removes a setting.

Raises:

PloneConfigurationError – If a key is not one of DEFAULT_KEYS or 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:

Profile

current_name(environ=None, cwd=None)[source]#

Name of the profile to use when none is given explicitly.

Parameters:
  • environ (Mapping[str, str] | None) – Environment; os.environ by default.

  • cwd (Path | None) – Directory where .plone-client.toml is looked for.

Returns:

The name, or an empty string.

Return type:

str

add(profile, *, replace=False)[source]#

Add a profile.

Parameters:
  • profile (Profile) – The profile.

  • replace (bool) – Replace a profile with the same name.

Raises:

PloneConfigurationError – If the name is taken.

Return type:

None

remove(name)[source]#

Remove a profile, also from the groups; a group left empty goes too.

Parameters:

name (str) – Profile name.

Returns:

The removed profile.

Return type:

Profile

to_mapping()[source]#

Contents of the configuration file.

Returns:

current and the defaults, profiles and groups tables.

Return type:

dict[str, Any]

save()[source]#

Write the configuration file, readable only by its owner.

Raises:

PloneConfigurationError – If tomlkit is 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:

Config

plone_client.profiles.settings_from_env(environ, *, prefix='PLONE_CLIENT_')[source]#

Client settings from environment variables.

Reads URL, USERNAME (or USER), PASSWORD, TOKEN, AUTH_METHOD, API_PREFIX, TIMEOUT, VERIFY (true, false or a CA bundle path), RETRIES, BACKOFF, READ_ONLY, TRANSITIONS (ids separated by commas), FRONTEND_URL and BLOCKS (a JSON object), each after the prefix. With prefix="REMOTE_", this reads the REMOTE_URL, REMOTE_USER and REMOTE_PASSWORD variables used by older scripts.

Parameters:
  • environ (Mapping[str, str]) – The environment.

  • prefix (str) – Prefix of the variable names.

Returns:

Keyword arguments for PloneClient.

Raises:

PloneConfigurationError – If the URL is not set.

Return type:

dict[str, Any]

Credentials#

Where the password or token of a profile is kept.

keyring (default)

The operating system’s secret store, through the keyring package: macOS Keychain, Windows Credential Locker, or the Secret Service on Linux. Entries are stored under the service plone-client:<profile>.

env

An environment variable, named by the profile’s secret_env (PLONE_CLIENT_PASSWORD by default). Handy in CI.

command

The output of a command, named by the profile’s secret_command, such as op read op://Private/site/password or pass show plone/site. The command runs without a shell.

none

No 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.keyring_service(profile)[source]#

Keyring service name of a profile.

Parameters:

profile (Profile) – The profile.

Returns:

plone-client:<profile name>.

Return type:

str

plone_client.credentials.keyring_account(profile)[source]#

Keyring account name of a profile.

Parameters:

profile (Profile) – The profile.

Returns:

The username, or token for token profiles without one.

Return type:

str

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:

str

plone_client.credentials.set_secret(profile, value)[source]#

Store the secret of a profile in the keyring.

Parameters:
  • profile (Profile) – The profile.

  • value (str) – The password or token.

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.

Parameters:

profile (Profile) – The profile.

Returns:

True if there was a secret to remove.

Return type:

bool

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_TOKEN when set, or the token in the keyring.

Raises:

PloneConfigurationError – If there is none, or it is too short.

Return type:

str

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

plone_client.credentials.generate_mcp_token()[source]#

Make a new random token for the MCP server and store it in the keyring.

Returns:

The token, for the MCP clients’ configuration.

Return type:

str

plone_client.credentials.delete_mcp_token()[source]#

Remove the token of the MCP server from the keyring.

Returns:

True if there was a token to remove.

Return type:

bool

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.

plone_client.utils.uid_from_ref(ref)[source]#

UID named by a reference, if the reference names one.

Two forms name a UID: uid:<UID> and a resolveuid link, the way Volto stores internal links (../resolveuid/<UID>, https://example.org/resolveuid/<UID>/@@download/file).

Parameters:

ref (str) – A path, URL or UID reference.

Returns:

The UID, or an empty string when ref is a plain path or URL.

Return type:

str

plone_client.utils.resolveuid_url(uid, suffix='')[source]#

Link to an item by UID, in the form Volto stores in blocks.

Parameters:
  • uid (str) – UID of the item.

  • suffix (str) – Text appended to the link, such as #section or /@@download/file.

Returns:

../resolveuid/<UID><suffix>.

Return type:

str