NAME
AnyEvent::MCP::Config - named servers and derived MCP credentials
SYNOPSIS
use AnyEvent::MCP::Config;
my $config = AnyEvent::MCP::Config::global_config;
my $token = $config->user_credentials ("agni")->[0][2];
my $url = $config->http_url ("agni", undef, path => "/");
DESCRIPTION
An MCP server and its clients often need matching credentials. Rather than maintaining a separate password for each server and user, this module can derive them from one private master secret. Users are defined by user.NAME = GENERATION in [global], [program PROGRAM] or [instance NAME], in that order of precedence. An absent global user.default is implicitly enabled at generation 1.
The shared file format is described in "GLOBAL CONFIGURATION" in AnyEvent::MCP. Loading this module does not read any files. global_config loads the configuration, ensures a persistent master secret exists and caches the initialized object for the process.
A missing secret is generated using AnyEvent::MCP::random_bytes and appended under a file lock. Failure to save the secret is fatal, rather than using a temporary secret that other processes cannot reproduce. A supplied invalid secret is an error. Changing or losing the master secret invalidates all credentials derived from it.
Derivation uses derive_secret with the random master key. The application namespace, purpose, program, instance name and username are separately length-prefixed, so distinct contexts derive different credentials. Deriving a password does not create an account or configure the server to accept it: authentication still belongs to the server.
METHODS
- $config = AnyEvent::MCP::Config::global_config (file => $file)
-
Return the process-global configuration object, loaded and initialized. The first call accepts the same arguments as
new, and ensures that the master secret is persistently stored. Later calls return the same object without rereading or reinitializing it. - $config = AnyEvent::MCP::Config->new (file => $file)
-
Construct an independent configuration object without reading or writing the file.
$filedefaults to the global configuration path. - $config->load
-
Reload the file, replacing the object's sections. A missing file yields an empty configuration; other read and parsing errors are fatal. Sections are available as
$config->{section}{$section}, each a hash reference of string values. Named servers use[instance NAME]. An optional raw file handle can be supplied when the caller already holds the file lock. - $config->save
-
Write the loaded sections back as canonical UTF-8 INI text, sorting sections and keys. Comments and original formatting are not retained. The caller must hold
AnyEvent::MCP::file_lockthrough the update. Returns the configuration object. - $config->ensure_secret
-
Ensure that
[global]contains a valid persistent master secret. If missing, lock and reread the file, generate a secret only if still absent, and append it without changing other settings. Fail if it cannot be saved or is invalid. Returns the configuration object. - $bytes = $config->derive_secret ($length, @info)
- $bytes = AnyEvent::MCP::Config->derive_secret ($length, @info)
-
Derive
$lengthsecret bytes from the configuration's master secret and an ordered list of context byte strings@info. The class form usesglobal_config, loading the default configuration on first use and reusing it thereafter. The object form uses that object's configuration, including one loaded from an explicit file.The same master secret and context always produce the same bytes. Use a distinctive application/purpose string as the first context field, followed by names or other values identifying the result:
my $secret = AnyEvent::MCP::Config->derive_secret ( 32, "my application token v1", AnyEvent::MCP::utf8enc ($name) );The result contains raw bytes; encode it yourself if a printable token is needed. This method does not add the result to a server's accepted tokens.
The fixed
anyevent-mcpcontext field is prepended automatically. Context fields are separately length-prefixed, so("ab", "c")and("a", "bc")have different contexts. Encode character strings explicitly, for example withAnyEvent::MCP::utf8enc. Context arguments are left unchanged.$lengthmust be an integer in 0..16320; zero returns an empty string. Shorter results are prefixes of longer results for the same master secret and context. Use distinct context fields for different purposes, rather than relying on different lengths to separate them.Derivation uses HKDF-SHA512 expansion, with each context field prefixed by its four-byte big-endian byte length. Changing or losing the master secret changes every result derived from it.
- $credential = $config->credential ($purpose, $name, $username)
-
Derives a 32-byte credential, returned as unpadded URL-safe Base64.
$purposeistoken.$nameis the instance name, and$usernameis optional. This is the older unmanaged derivation API; its result is not automatically accepted by a server. Managed credentials are enumerated byuser_credentials.Credentials use the context
("anyevent-mcp", "token", PROGRAM, NAME, USER). PROGRAM is the invoked basename, with a trailing.plor.perlremoved. Changing the program or instance name changes the credential. A credential derived with$usernameis not automatically accepted by the server. This method neither requires a server section nor configures authentication. - $users = $config->users ($instance, $program)
-
Return effective user definitions keyed by username, each with
scope(global, program or instance) and signedgeneration. Inheritance is global, program, instance; a negative generation disables without fallback. - $credentials = $config->user_credentials ($instance, $program)
-
Return enabled users as
[[USERNAME, PRINCIPAL, TOKEN]...]with default first. The principal isglobal:NAME,program:NAME, orinstance:NAME. HKDF context includes program, instance, scope, user and generation. Rotating a generation changes the token but preserves saved user permissions. - $user = $config->connect_user ($instance, $program)
-
Return the username allowed to register private Vim, browser WebSocket, or multibroker reverse-MCP connections.
connect_userinherits through the usual scopes and defaults todefault. Revoking that user disables these connections until its generation is renewed or another user is selected. - $program = AnyEvent::MCP::Config::program_name ()
-
Returns the invoked program basename, stripping
.plor.perl. An inline Perl invocation usesperl. This identity also selects the[program PROGRAM]configuration section; it is independent of routing aliases. - $user = AnyEvent::MCP::Config::user_name ($user)
-
Validate a managed username (ASCII letter or underscore, followed by letters, digits, underscores or hyphens). Instance names are validated by "SMALL UTILITIES" in AnyEvent::MCP.
- @options = AnyEvent::MCP::Config::http_getopt (\$name, \$bind, \$print_url, \@tokens)
-
Return standard
Getopt::Longoptions referring to the caller's scalars. - $port = $config->server_port ($name)
-
Derive a stable default port in 16384..32767 from the master secret and program basename and service-instance name. Collisions produce ordinary listener bind errors.
- %settings = $config->http_settings ($name, $bind, $default_port)
-
Resolve HTTP settings from
[instance NAME]and an optional command-linebindoverride. The default is IPv4 loopback and the name-derived port; an optionaldefault_portreplaces the derived port when no bind port is specified. The bind setting acceptsADDRESS:PORT,[IPv6]:PORT,ADDRESS, and:PORT(which keeps the default loopback address). Hostnames are resolved once when settings are obtained; their original spelling is advertised unlessurl_hostoverrides it. The returned options includename,host,portandtokens, plus configuredpath,url_hostandurl_scheme. This does not start a listener. - @rules = $config->auto_rules ($name)
-
Return ordered automatic permission rules from
[program PROGRAM]and[instance NAME].auto-rule.SUFFIX = allow|deny TOOL[,ACTION[,CAPABILITY]]entries are sorted by key. The suffix is an arbitrary ordering label; instance entries override matching program entries, and an empty value disables an inherited entry. Command-line rules take precedence over these defaults. - $url = $config->http_url ($name, $bind, %options)
-
Format a URL containing the first accepted token, without listening. Port zero cannot be used because the kernel has not yet selected a port. When the token is derived, the master secret must be persistently stored, so the next process derives the same URL. Explicit static tokens and
auth => "none"do not require that persistence check.
INI FUNCTIONS
These functions work with Unicode character strings, not octets. Use "file_load" in AnyEvent::MCP and "file_save" in AnyEvent::MCP for UTF-8 file I/O. Binary values belong in Base64 or hexadecimal form.
- $sections = AnyEvent::MCP::Config::parse_ini ($text, $filename)
-
Parse Unicode INI text into
[[NAME, {KEY => VALUE}], ...]. Sections retain file order, including repeated section names and the initial unnamed section"". Duplicate keys within one section use the final value.$filenameis optional, for line-numbered errors. - $merged = AnyEvent::MCP::Config::merge_sections ($sections, $default)
-
Return a hash mapping section names to key/value hashes, with later sections overriding earlier ones. When
$defaultis given, unnamed sections use that name (globalfor global configuration andaccountfor IMAP accounts). Use the original ordered list instead for files where repeated sections are meaningful, such as permission rules. - $text = AnyEvent::MCP::Config::serialize_ini ($sections)
-
Serialize an ordered section list to canonical INI text. Section order is preserved; keys within each section are sorted. Values must be single-line character strings. Comments and whitespace formatting are deliberately not preserved on rewrite.