feat: mcpctl mcptoken verbs + mcpd auth dispatch + audit plumbing

Adds the end-to-end CLI surface for McpTokens and the mcpd auth dispatch
that recognizes them.

mcpd auth middleware:
  - Dispatch on the `mcpctl_pat_` bearer prefix. McpToken bearers resolve
    through a new `findMcpToken(hash)` dep, populating `request.mcpToken`
    and `request.userId = ownerId`. Everything else follows the existing
    session path.
  - Returns 401 for revoked / expired / unknown tokens.
  - Global RBAC hook now threads `mcpTokenSha` into `canAccess` /
    `canRunOperation` / `getAllowedScope`, and enforces a hard
    project-scope check: a McpToken principal can only hit
    `/api/v1/projects/<its-project>/...`.

CLI verbs:
  - `mcpctl create mcptoken <name> -p <proj> [--rbac empty|clone]
    [--bind role:view,resource:servers] [--ttl 30d|never|ISO]
    [--description ...] [--force]` — returns the raw token once.
  - `mcpctl get mcptokens [-p <proj>]` — table with
    NAME/PROJECT/PREFIX/CREATED/LAST USED/EXPIRES/STATUS.
  - `mcpctl get mcptoken <name> -p <proj>` and
    `mcpctl describe mcptoken <name> -p <proj>` — describe surfaces the
    auto-created RBAC bindings.
  - `mcpctl delete mcptoken <name> -p <proj>`.
  - `apply -f` support with `kind: mcptoken`. Tokens are immutable, so
    apply creates if missing and skips if the name is already active.

Audit plumbing:
  - `AuditEvent` / collector now carry optional `tokenName` / `tokenSha`.
    `setSessionMcpToken` sits alongside `setSessionUserName`; both feed a
    per-session principal map used at emit time.
  - `AuditEventService` query accepts `tokenName` / `tokenSha` filters.
  - Console `AuditEvent` type carries the new fields so a follow-up can
    add a TOKEN column.

Completions regenerated. 1764/1764 tests pass workspace-wide.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Michal
2026-04-17 01:12:43 +01:00
parent efcfeeab65
commit a151b2e756
17 changed files with 539 additions and 13 deletions

View File

@@ -132,6 +132,15 @@ const ProjectSpecSchema = z.object({
servers: z.array(z.string()).default([]),
});
const McpTokenSpecSchema = z.object({
name: z.string().min(1).max(100).regex(/^[a-z0-9-]+$/),
project: z.string().min(1),
description: z.string().default(''),
expiresAt: z.union([z.string().datetime(), z.null()]).optional(),
rbacMode: z.enum(['empty', 'clone']).default('empty'),
bindings: z.array(RbacRoleBindingSchema).default([]),
});
const ApplyConfigSchema = z.object({
secrets: z.array(SecretSpecSchema).default([]),
servers: z.array(ServerSpecSchema).default([]),
@@ -143,6 +152,7 @@ const ApplyConfigSchema = z.object({
rbacBindings: z.array(RbacBindingSpecSchema).default([]),
rbac: z.array(RbacBindingSpecSchema).default([]),
prompts: z.array(PromptSpecSchema).default([]),
mcptokens: z.array(McpTokenSpecSchema).default([]),
}).transform((data) => ({
...data,
// Merge rbac into rbacBindings so both keys work
@@ -182,6 +192,7 @@ export function createApplyCommand(deps: ApplyCommandDeps): Command {
if (config.serverattachments.length > 0) log(` ${config.serverattachments.length} serverattachment(s)`);
if (config.rbacBindings.length > 0) log(` ${config.rbacBindings.length} rbacBinding(s)`);
if (config.prompts.length > 0) log(` ${config.prompts.length} prompt(s)`);
if (config.mcptokens.length > 0) log(` ${config.mcptokens.length} mcptoken(s)`);
return;
}
@@ -217,6 +228,7 @@ const KIND_TO_RESOURCE: Record<string, string> = {
prompt: 'prompts',
promptrequest: 'promptrequests',
serverattachment: 'serverattachments',
mcptoken: 'mcptokens',
};
/**
@@ -529,6 +541,46 @@ async function applyConfig(client: ApiClient, config: ApplyConfig, log: (...args
log(`Error applying prompt '${prompt.name}': ${err instanceof Error ? err.message : err}`);
}
}
// --- McpTokens ---
// Apply semantics: tokens are immutable (their secret is minted once). If an
// active token with the same name+project already exists we skip, logging the
// state. Otherwise we create and log the raw token (shown exactly once).
for (const tok of config.mcptokens) {
try {
const proj = await cachedFindByName('projects', tok.project);
if (!proj) {
log(`Error applying mcptoken '${tok.name}': project '${tok.project}' not found`);
continue;
}
// Check if an active one already exists
const existing = await client
.get<Array<{ id: string; name: string; status: string }>>(`/api/v1/mcptokens?projectName=${encodeURIComponent(tok.project)}`)
.catch(() => []);
const active = existing.find((t) => t.name === tok.name && t.status === 'active');
if (active) {
log(`mcptoken '${tok.name}' already active in project '${tok.project}' — skipped (tokens are immutable)`);
continue;
}
const body: Record<string, unknown> = {
name: tok.name,
projectId: proj.id,
description: tok.description,
rbacMode: tok.rbacMode,
bindings: tok.bindings,
};
if (tok.expiresAt !== undefined) body.expiresAt = tok.expiresAt;
const created = await withRetry(() => client.post<{ id: string; name: string; token: string }>('/api/v1/mcptokens', body));
log(`Created mcptoken: ${tok.name} (project: ${tok.project})`);
log(` token: ${created.token}`);
log(' (raw token shown once — copy it now)');
} catch (err) {
log(`Error applying mcptoken '${tok.name}': ${err instanceof Error ? err.message : err}`);
}
}
}
async function findByField<T extends string>(client: ApiClient, resource: string, field: T, value: string): Promise<unknown | null> {

View File

@@ -23,6 +23,9 @@ export interface AuditEvent {
serverName: string | null;
correlationId: string | null;
parentEventId: string | null;
userName?: string | null;
tokenName?: string | null;
tokenSha?: string | null;
payload: Record<string, unknown>;
}

View File

@@ -11,6 +11,37 @@ function collect(value: string, prev: string[]): string[] {
return [...prev, value];
}
/**
* Parse a `--ttl` value.
*
* - `"never"` → null (no expiry)
* - `"30d"`, `"12h"`, `"2w"`, `"90m"`, `"60s"` → ISO8601 string relative to now
* - An ISO8601 datetime → returned as-is
*/
function parseTtl(value: string): string | null {
const trimmed = value.trim();
if (trimmed.toLowerCase() === 'never') return null;
const match = trimmed.match(/^(\d+)([smhdw])$/i);
if (match) {
const amount = Number(match[1]);
const unit = match[2]!.toLowerCase();
const multipliers: Record<string, number> = {
s: 1000,
m: 60 * 1000,
h: 3600 * 1000,
d: 86400 * 1000,
w: 7 * 86400 * 1000,
};
return new Date(Date.now() + amount * multipliers[unit]!).toISOString();
}
// Try to parse as ISO8601
const parsed = new Date(trimmed);
if (isNaN(parsed.getTime())) {
throw new Error(`Invalid --ttl '${value}'. Expected 'never', a duration like '30d' / '12h', or an ISO8601 datetime.`);
}
return parsed.toISOString();
}
interface ServerEnvEntry {
name: string;
value?: string;
@@ -372,6 +403,83 @@ export function createCreateCommand(deps: CreateCommandDeps): Command {
}
});
// --- create mcptoken ---
cmd.command('mcptoken')
.description('Create a project-scoped API token for HTTP-mode mcplocal. The raw token is printed once.')
.argument('<name>', 'Token name (unique within a project)')
.requiredOption('-p, --project <name>', 'Project this token is bound to')
.option('--rbac <mode>', "Base RBAC: 'empty' (default, no bindings) or 'clone' (snapshot creator's perms)", 'empty')
.option(
'--bind <entry>',
'Additional role binding as key:value pairs, e.g. "role:view,resource:servers" or "action:logs" (repeat for multiple). Creator perms are the ceiling.',
collect,
[],
)
.option('--ttl <duration>', "Expiry: '30d', '12h', 'never', or an ISO8601 datetime")
.option('--description <text>', 'Freeform description')
.option('--force', 'Revoke any existing active token with this name, then create a new one')
.action(async (name: string, opts) => {
// Resolve project name → id (mcpd's create route accepts either, but resolve client-side for clearer errors)
const projectId = await resolveNameOrId(client, 'projects', opts.project as string);
const bindings = (opts.bind as string[]).map((entry: string) => parseRoleBinding(entry));
const rbacMode = (opts.rbac as string).toLowerCase();
if (rbacMode !== 'empty' && rbacMode !== 'clone') {
throw new Error(`--rbac must be 'empty' or 'clone' (got '${opts.rbac as string}')`);
}
let expiresAt: string | null | undefined;
if (opts.ttl !== undefined) {
expiresAt = parseTtl(opts.ttl as string);
}
const body: Record<string, unknown> = {
name,
projectId,
rbacMode,
bindings,
};
if (expiresAt !== undefined) body.expiresAt = expiresAt;
if (opts.description !== undefined) body.description = opts.description;
type Created = {
id: string;
name: string;
projectName: string;
tokenPrefix: string;
token: string;
expiresAt: string | null;
};
const doCreate = async (): Promise<Created> => client.post<Created>('/api/v1/mcptokens', body);
let created: Created;
try {
created = await doCreate();
} catch (err) {
if (err instanceof ApiError && err.status === 409 && opts.force) {
// Find the existing active token by name+project and revoke it, then retry.
const existing = (await client.get<Array<{ id: string; name: string }>>(
`/api/v1/mcptokens?projectName=${encodeURIComponent(opts.project as string)}`,
)).find((r) => r.name === name);
if (!existing) throw err;
await client.post(`/api/v1/mcptokens/${existing.id}/revoke`, {});
created = await doCreate();
} else {
throw err;
}
}
log(`mcptoken '${created.name}' created (project: ${created.projectName}, id: ${created.id})`);
log('');
log('Copy this token now — it will NOT be shown again:');
log('');
log(` ${created.token}`);
log('');
log(`Export it with: export MCPCTL_TOKEN=${created.token}`);
});
// --- create prompt ---
cmd.command('prompt')
.description('Create an approved prompt')

View File

@@ -29,6 +29,27 @@ export function createDeleteCommand(deps: DeleteCommandDeps): Command {
return;
}
// Mcptokens: names are scoped to a project, so require --project unless the caller passes a CUID
if (resource === 'mcptokens') {
let tokenId: string;
if (/^c[a-z0-9]{24}/.test(idOrName)) {
tokenId = idOrName;
} else {
if (!opts.project) {
throw new Error('--project is required to delete an mcptoken by name (or pass the id).');
}
const items = await client.get<Array<{ id: string; name: string }>>(
`/api/v1/mcptokens?projectName=${encodeURIComponent(opts.project)}`,
);
const match = items.find((i) => i.name === idOrName);
if (!match) throw new Error(`mcptoken '${idOrName}' not found in project '${opts.project}'`);
tokenId = match.id;
}
await client.delete(`/api/v1/mcptokens/${tokenId}`);
log(`mcptoken '${idOrName}' deleted.`);
return;
}
// Resolve name → ID for any resource type
let id: string;
try {

View File

@@ -503,6 +503,42 @@ function formatRbacDetail(rbac: Record<string, unknown>): string {
return lines.join('\n');
}
function formatMcpTokenDetail(token: Record<string, unknown>, allRbac: RbacDef[]): string {
const lines: string[] = [];
lines.push(`=== McpToken: ${token.name} ===`);
lines.push(`${pad('Name:')}${token.name}`);
lines.push(`${pad('Project:')}${token.projectName ?? token.projectId ?? '-'}`);
lines.push(`${pad('Status:')}${token.status ?? '-'}`);
lines.push(`${pad('Prefix:')}${token.tokenPrefix ?? '-'}`);
if (token.description) lines.push(`${pad('Description:')}${token.description}`);
lines.push(`${pad('Owner:')}${token.ownerEmail ?? token.ownerId ?? '-'}`);
lines.push(`${pad('Created:')}${token.createdAt ?? '-'}`);
lines.push(`${pad('Last Used:')}${token.lastUsedAt ?? 'never'}`);
lines.push(`${pad('Expires:')}${token.expiresAt ?? 'never'}`);
if (token.revokedAt) lines.push(`${pad('Revoked At:')}${token.revokedAt}`);
// Find the auto-created RbacDefinition (subject McpToken:<sha>) to surface bindings.
// We don't know the sha from the describe response — match by convention: name 'mcptoken-<id>'.
const rbacDef = allRbac.find((r) => r.name === `mcptoken-${token.id as string}`);
if (rbacDef && Array.isArray(rbacDef.roleBindings) && rbacDef.roleBindings.length > 0) {
lines.push('');
lines.push('Bindings:');
for (const b of rbacDef.roleBindings as Array<{ role: string; resource?: string; action?: string; name?: string }>) {
if (b.action !== undefined) {
lines.push(` run ${b.action}`);
} else if (b.resource !== undefined) {
lines.push(` ${b.role} ${b.resource}${b.name !== undefined ? `/${b.name}` : ''}`);
}
}
}
lines.push('');
lines.push('Metadata:');
lines.push(` ${pad('ID:', 12)}${token.id}`);
return lines.join('\n');
}
async function formatPromptDetail(prompt: Record<string, unknown>, client?: ApiClient): Promise<string> {
const lines: string[] = [];
lines.push(`=== Prompt: ${prompt.name} ===`);
@@ -801,6 +837,14 @@ export function createDescribeCommand(deps: DescribeCommandDeps): Command {
case 'prompts':
deps.log(await formatPromptDetail(item, deps.client));
break;
case 'mcptokens': {
// Fetch the auto-created RbacDefinition (if any) so bindings are visible in describe.
const rbacForToken = await deps.client
.get<RbacDef[]>('/api/v1/rbac')
.catch(() => [] as RbacDef[]);
deps.log(formatMcpTokenDetail(item, rbacForToken));
break;
}
default:
deps.log(formatGenericDetail(item));
}

View File

@@ -119,6 +119,27 @@ const rbacColumns: Column<RbacRow>[] = [
{ header: 'ID', key: 'id' },
];
interface McpTokenRow {
id: string;
name: string;
projectName: string;
tokenPrefix: string;
createdAt: string;
lastUsedAt: string | null;
expiresAt: string | null;
status: 'active' | 'revoked' | 'expired';
}
const mcpTokenColumns: Column<McpTokenRow>[] = [
{ header: 'NAME', key: 'name', width: 24 },
{ header: 'PROJECT', key: 'projectName', width: 20 },
{ header: 'PREFIX', key: 'tokenPrefix', width: 18 },
{ header: 'CREATED', key: (r) => new Date(r.createdAt).toLocaleString(), width: 20 },
{ header: 'LAST USED', key: (r) => r.lastUsedAt ? new Date(r.lastUsedAt).toLocaleString() : '-', width: 20 },
{ header: 'EXPIRES', key: (r) => r.expiresAt ? new Date(r.expiresAt).toLocaleString() : 'never', width: 20 },
{ header: 'STATUS', key: 'status', width: 10 },
];
const secretColumns: Column<SecretRow>[] = [
{ header: 'NAME', key: 'name' },
{ header: 'KEYS', key: (r) => Object.keys(r.data).join(', ') || '-', width: 40 },
@@ -242,6 +263,8 @@ function getColumnsForResource(resource: string): Column<Record<string, unknown>
return serverAttachmentColumns as unknown as Column<Record<string, unknown>>[];
case 'proxymodels':
return proxymodelColumns as unknown as Column<Record<string, unknown>>[];
case 'mcptokens':
return mcpTokenColumns as unknown as Column<Record<string, unknown>>[];
default:
return [
{ header: 'ID', key: 'id' as keyof Record<string, unknown> },
@@ -263,6 +286,7 @@ const RESOURCE_KIND: Record<string, string> = {
prompts: 'prompt',
promptrequests: 'promptrequest',
serverattachments: 'serverattachment',
mcptokens: 'mcptoken',
};
/**

View File

@@ -27,6 +27,10 @@ export const RESOURCE_ALIASES: Record<string, string> = {
proxymodel: 'proxymodels',
proxymodels: 'proxymodels',
pm: 'proxymodels',
mcptoken: 'mcptokens',
mcptokens: 'mcptokens',
token: 'mcptokens',
tokens: 'mcptokens',
all: 'all',
};
@@ -72,6 +76,21 @@ export function stripInternalFields(obj: Record<string, unknown>): Record<string
delete result[key];
}
// McpToken-specific: promote projectName → project; drop secret/derived fields
if ('tokenHash' in result || 'tokenPrefix' in result) {
delete result.tokenHash;
delete result.tokenPrefix;
delete result.lastUsedAt;
delete result.revokedAt;
delete result.status;
delete result.ownerEmail;
if (typeof result.projectName === 'string') {
result.project = result.projectName;
delete result.projectName;
delete result.projectId;
}
}
// Rename linkTarget → link for cleaner YAML
if ('linkTarget' in result) {
result.link = result.linkTarget;

View File

@@ -99,6 +99,25 @@ export function createProgram(): Command {
}
}
// --project scoping for mcptokens
if (!nameOrId && resource === 'mcptokens' && projectName) {
return client.get<unknown[]>(`/api/v1/mcptokens?projectName=${encodeURIComponent(projectName)}`);
}
// Name-based lookup for mcptokens: names are unique only within a project
if (nameOrId && resource === 'mcptokens' && !/^c[a-z0-9]{24}/.test(nameOrId)) {
if (!projectName) {
throw new Error('mcptoken names are scoped to a project — pass --project <name> or use the token id (cuid)');
}
const items = await client.get<Array<{ id: string; name: string }>>(
`/api/v1/mcptokens?projectName=${encodeURIComponent(projectName)}`,
);
const match = items.find((i) => i.name === nameOrId);
if (!match) throw new Error(`mcptoken '${nameOrId}' not found in project '${projectName}'`);
const item = await client.get(`/api/v1/mcptokens/${match.id}`);
return [item];
}
if (nameOrId) {
// Glob pattern — use query param filtering
if (nameOrId.includes('*')) {
@@ -132,6 +151,19 @@ export function createProgram(): Command {
return client.get(`/api/v1/${resource}/${match.id as string}`);
}
// Mcptokens: names are project-scoped. CUIDs pass straight through.
if (resource === 'mcptokens' && !/^c[a-z0-9]{24}/.test(nameOrId)) {
if (!projectName) {
throw new Error('mcptoken names are scoped to a project — pass --project <name> or use the token id (cuid)');
}
const items = await client.get<Array<Record<string, unknown>>>(
`/api/v1/mcptokens?projectName=${encodeURIComponent(projectName)}`,
);
const match = items.find((item) => item.name === nameOrId);
if (!match) throw new Error(`mcptoken '${nameOrId}' not found in project '${projectName}'`);
return client.get(`/api/v1/mcptokens/${match.id as string}`);
}
let id: string;
try {
id = await resolveNameOrId(client, resource, nameOrId);