Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions docs/agents/adding-capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@ runs. Missing secrets still fail with the same "secret not found" guidance used
elsewhere, and secret-bearing capability inputs still require an authenticated
user.

When a secret has an `allowed_capabilities` policy, Kody also checks that the
current capability name is explicitly listed before resolving the placeholder.
An empty `allowed_capabilities` list means the secret is unrestricted for
capability-input use.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cursoragent I think this is now inaccurate. An empty list should definitely mean it is completely restricted.

@cursor cursor Bot Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Wrong property name breaks app-scoped capability allowlist saves
    • Renamed the capability save input to use storageContext/StorageContext and updated the caller so app-scoped secrets resolve the correct bucket.

Create PR

Preview (913e37f621)
diff --git a/docs/agents/adding-capabilities.md b/docs/agents/adding-capabilities.md
--- a/docs/agents/adding-capabilities.md
+++ b/docs/agents/adding-capabilities.md
@@ -104,6 +104,11 @@
 elsewhere, and secret-bearing capability inputs still require an authenticated
 user.
 
+When a secret has an `allowed_capabilities` policy, Kody also checks that the
+current capability name is explicitly listed before resolving the placeholder.
+An empty `allowed_capabilities` list means no capability is allowed to resolve
+the secret until entries are added.
+
 Use this for capabilities that need to accept a secret value as an argument but
 are not themselves the host-approval boundary. Good fits include:
 
@@ -284,6 +289,8 @@
 
 - annotate only the exact credential fields, not the whole object
 - prefer this for local persistence or device-side credential flows
+- tell users which capability names should be added to a secret's
+  `allowed_capabilities` policy when a workflow depends on restricted secrets
 - avoid using it for generic remote API wrappers where fetch-time host approval
   should remain the enforcement point
 
@@ -295,8 +302,8 @@
   ranked results
 - use `execute` to confirm the capability runs correctly
 
-Prefer E2E tests in `packages/worker/src/mcp/*.mcp-e2e.test.ts` for the real
-MCP contract.
+Prefer E2E tests in `packages/worker/src/mcp/*.mcp-e2e.test.ts` for the real MCP
+contract.
 
 Registry invariants (duplicate capability names, domain/capability mismatches,
 duplicate domain registration) are covered in

diff --git a/docs/agents/secret-host-approval.md b/docs/agents/secret-host-approval.md
--- a/docs/agents/secret-host-approval.md
+++ b/docs/agents/secret-host-approval.md
@@ -5,18 +5,19 @@
 
 ## Rule
 
-Allowed outbound hosts for a secret are privileged policy, not normal secret
+Allowed outbound hosts for a secret and allowed capabilities for direct
+capability-input secret resolution are privileged policy, not normal secret
 metadata.
 
-That policy must not be created, widened, or modified by:
+Those policies must not be created, widened, or modified by:
 
 - MCP tools
 - execute-time sandboxed code
 - generated UI code
 - capability handlers that serve agent-driven secret creation or update flows
 
-Allowed outbound hosts may only be changed through the authenticated account
-admin UI approval flow.
+Allowed outbound hosts and allowed capabilities may only be changed through the
+authenticated account admin UI.
 
 In this repo, that means the user must approve host access through the account
 secrets experience, such as `/account/secrets` and the focused approval route at
@@ -29,7 +30,7 @@
 UI.
 
 Saving or updating a secret value does not authorize sending that secret to any
-host.
+host or passing it into any capability.
 
 If an outbound request uses a placeholder such as `{{secret:name}}` and the
 target host is not already approved for that secret, the correct behavior is:
@@ -42,16 +43,22 @@
 ## What agents must not do
 
 Do not design or document any MCP capability, generated UI helper, or client
-library that allows agent-controlled writes to a secret's allowed hosts.
+library that allows agent-controlled writes to a secret's allowed hosts or
+allowed capabilities.
 
 Specifically, do not:
 
 - add `allowed_hosts` or equivalent fields to MCP-facing secret create/update
   inputs
+- add `allowed_capabilities` or equivalent fields to MCP-facing secret
+  create/update inputs
 - imply that a generated UI can self-authorize a host just because it can save a
   secret
+- imply that execute-time capability calls can widen which capabilities may
+  consume a secret
 - imply that execute-time code can widen egress permissions
-- treat host approval as ordinary secret metadata editing
+- treat host approval or capability allowlists as ordinary secret metadata
+  editing
 
 If a workflow would be smoother by auto-approving a host, the fix should be
 better guidance, helper APIs, or UX around the approval flow, not a new write
@@ -62,7 +69,10 @@
 When writing capability descriptions or agent-facing docs:
 
 - say explicitly that secret save/update does not grant outbound use
+- say explicitly that secret save/update does not grant capability access
 - say explicitly that only the authenticated account admin UI can approve hosts
+- say explicitly that only the authenticated account admin UI can restrict which
+  capabilities may consume a secret directly
 - tell agents to inspect secret metadata before making a secret-bearing request
 - tell agents to surface the approval link and stop on deny
 
@@ -84,6 +94,9 @@
 for example to store credentials on a local connector or pass them into a
 device-local action.
 
+If a secret has an allowed-capabilities policy, Kody enforces that allowlist by
+capability name before resolving the placeholder for the handler.
+
 Use it narrowly:
 
 - mark only the exact sensitive fields
@@ -105,11 +118,13 @@
 - save those values as secrets
 - save and read back non-secret values for public configuration
 - inspect secret metadata, including current allowed hosts
+- inspect secret metadata, including current allowed capabilities
 - present approval links returned from blocked requests
 
 Generated UIs may not:
 
 - set allowed hosts directly
+- set allowed capabilities directly
 - bypass the admin approval route
 - silently retry secret-bearing requests after a deny
 - use `executeCode(...)` as a general string interpolation mechanism for

diff --git a/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts b/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts
--- a/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts
+++ b/packages/worker/client/mcp-apps/generated-ui-shell.node.test.ts
@@ -215,7 +215,6 @@
 		errorMessage: 'Saved app not found for this user.',
 	})
 })
-
 test('buildLocalMessageLogRuntimeSource logs sendMessage locally outside hosted contexts', () => {
 	const originalWindow = globalThis.window
 	const originalDocument = globalThis.document

diff --git a/packages/worker/client/mcp-apps/generated-ui-shell.ts b/packages/worker/client/mcp-apps/generated-ui-shell.ts
--- a/packages/worker/client/mcp-apps/generated-ui-shell.ts
+++ b/packages/worker/client/mcp-apps/generated-ui-shell.ts
@@ -22,6 +22,7 @@
 	description: string
 	app_id: string | null
 	allowed_hosts: Array<string>
+	allowed_capabilities: Array<string>
 	created_at: string
 	updated_at: string
 	ttl_ms: number | null
@@ -772,6 +773,10 @@
 				(secret.app_id == null || typeof secret.app_id === 'string') &&
 				Array.isArray(secret.allowed_hosts) &&
 				secret.allowed_hosts.every((host) => typeof host === 'string') &&
+				Array.isArray(secret.allowed_capabilities) &&
+				secret.allowed_capabilities.every(
+					(capability) => typeof capability === 'string',
+				) &&
 				typeof secret.created_at === 'string' &&
 				typeof secret.updated_at === 'string' &&
 				(secret.ttl_ms == null ||

diff --git a/packages/worker/client/routes/account-secrets.tsx b/packages/worker/client/routes/account-secrets.tsx
--- a/packages/worker/client/routes/account-secrets.tsx
+++ b/packages/worker/client/routes/account-secrets.tsx
@@ -42,6 +42,7 @@
 	appId: string | null
 	appTitle: string | null
 	allowedHosts: Array<string>
+	allowedCapabilities: Array<string>
 	createdAt: string
 	updatedAt: string
 	ttlMs: number | null
@@ -68,6 +69,7 @@
 	description: string
 	value: string
 	allowedHosts: Array<string>
+	allowedCapabilities: Array<string>
 }
 
 type SelectionState = {
@@ -108,10 +110,56 @@
 		description: '',
 		value: '',
 		allowedHosts: [''],
+		allowedCapabilities: [''],
 	}
 }
 
+function coerceStringRows(list: Array<unknown>): Array<string> {
+	return list.filter((item): item is string => typeof item === 'string')
+}
+
+/** Matches server `normalizeAllowedHosts` in `#mcp/secrets/allowed-hosts.ts`. */
+function clientNormalizeAllowedHosts(hosts: Array<string>): Array<string> {
+	return Array.from(
+		new Set(
+			hosts
+				.map((host) => host.trim().toLowerCase())
+				.filter((host) => host.length > 0),
+		),
+	).sort()
+}
+
+/** Matches server `normalizeAllowedCapabilities` in `#mcp/secrets/allowed-capabilities.ts`. */
+function clientNormalizeAllowedCapabilities(
+	capabilities: Array<string>,
+): Array<string> {
+	return Array.from(
+		new Set(
+			capabilities
+				.map((value) => value.trim())
+				.filter((value) => value.length > 0),
+		),
+	).sort((left, right) => left.localeCompare(right))
+}
+
+function collectRepeatedTextRows(
+	form: HTMLFormElement,
+	listName: 'allowed-hosts' | 'allowed-capabilities',
+): Array<string> {
+	const root = form.querySelector(`[data-repeat-list="${listName}"]`)
+	if (!root) return []
+	const out: Array<string> = []
+	for (const row of root.children) {
+		if (!(row instanceof HTMLElement)) continue
+		const input = row.querySelector('input[type="text"]')
+		if (input instanceof HTMLInputElement) out.push(input.value)
+	}
+	return out
+}
+
 function createEditorStateFromSecret(secret: SecretDetail): EditorState {
+	const allowedHosts = coerceStringRows(secret.allowedHosts)
+	const allowedCapabilities = coerceStringRows(secret.allowedCapabilities)
 	return {
 		currentId: secret.id,
 		name: secret.name,
@@ -119,7 +167,9 @@
 		appId: secret.appId ?? '',
 		description: secret.description,
 		value: secret.value,
-		allowedHosts: secret.allowedHosts.length > 0 ? secret.allowedHosts : [''],
+		allowedHosts: allowedHosts.length > 0 ? allowedHosts : [''],
+		allowedCapabilities:
+			allowedCapabilities.length > 0 ? allowedCapabilities : [''],
 	}
 }
 
@@ -255,6 +305,7 @@
 			secret.appTitle ?? '',
 			secret.scope,
 			...secret.allowedHosts,
+			...secret.allowedCapabilities,
 		]
 			.join(' ')
 			.toLowerCase()
@@ -435,11 +486,19 @@
 		event.preventDefault()
 		if (saveState !== 'idle') return
 
+		const form = event.currentTarget as HTMLFormElement
+
 		saveState = 'saving'
 		message = null
 		handle.update()
 
 		try {
+			const allowedHosts = clientNormalizeAllowedHosts(
+				collectRepeatedTextRows(form, 'allowed-hosts'),
+			)
+			const allowedCapabilities = clientNormalizeAllowedCapabilities(
+				collectRepeatedTextRows(form, 'allowed-capabilities'),
+			)
 			const response = await fetch(accountSecretsApiPath, {
 				method: 'POST',
 				headers: {
@@ -455,7 +514,8 @@
 					appId: editorState.scope === 'app' ? editorState.appId : null,
 					description: editorState.description,
 					value: editorState.value,
-					allowedHosts: editorState.allowedHosts,
+					allowedHosts,
+					allowedCapabilities,
 				}),
 			})
 			if (response.status === 401) {
@@ -569,6 +629,37 @@
 		handle.update()
 	}
 
+	function updateAllowedCapability(index: number, value: string) {
+		editorState = {
+			...editorState,
+			allowedCapabilities: editorState.allowedCapabilities.map(
+				(capabilityName, capabilityIndex) =>
+					capabilityIndex === index ? value : capabilityName,
+			),
+		}
+		handle.update()
+	}
+
+	function addAllowedCapability() {
+		editorState = {
+			...editorState,
+			allowedCapabilities: [...editorState.allowedCapabilities, ''],
+		}
+		handle.update()
+	}
+
+	function removeAllowedCapability(index: number) {
+		const nextCapabilities = editorState.allowedCapabilities.filter(
+			(_capabilityName, capabilityIndex) => capabilityIndex !== index,
+		)
+		editorState = {
+			...editorState,
+			allowedCapabilities:
+				nextCapabilities.length > 0 ? nextCapabilities : [''],
+		}
+		handle.update()
+	}
+
 	return () => {
 		const currentHref = getCurrentHref()
 		const selection = getSelectionState(currentHref)
@@ -1181,10 +1272,13 @@
 											a secret can be used.
 										</p>
 									</div>
-									<div css={{ display: 'grid', gap: spacing.sm }}>
+									<div
+										css={{ display: 'grid', gap: spacing.sm }}
+										data-repeat-list="allowed-hosts"
+									>
 										{editorState.allowedHosts.map((host, index) => (
 											<div
-												key={`${index}-${host}`}
+												key={index}
 												css={{
 													display: 'grid',
 													gridTemplateColumns: 'minmax(0, 1fr) auto',
@@ -1195,9 +1289,9 @@
 												}}
 											>
 												<input
-													type="text"
-													value={host}
-													placeholder="api.example.com"
+														type="text"
+														value={typeof host === 'string' ? host : ''}
+														placeholder="api.example.com"
 													on={{
 														input: (event) =>
 															updateAllowedHost(
@@ -1228,6 +1322,72 @@
 									</div>
 								</div>
 
+								<div css={{ display: 'grid', gap: spacing.sm }}>
+									<div css={{ display: 'grid', gap: spacing.xs }}>
+										<span css={fieldLabelCss}>Allowed capabilities</span>
+										<p css={{ margin: 0, color: colors.textMuted }}>
+											Only capabilities listed here can resolve this secret
+											when used with an
+											<code> x-kody-secret </code>
+											input.
+										</p>
+									</div>
+									<div
+										css={{ display: 'grid', gap: spacing.sm }}
+										data-repeat-list="allowed-capabilities"
+									>
+										{editorState.allowedCapabilities.map(
+											(capabilityName, index) => (
+												<div
+													key={index}
+													css={{
+														display: 'grid',
+														gridTemplateColumns: 'minmax(0, 1fr) auto',
+														gap: spacing.sm,
+														[mq.mobile]: {
+															gridTemplateColumns: '1fr',
+														},
+													}}
+												>
+													<input
+														type="text"
+														value={
+															typeof capabilityName === 'string'
+																? capabilityName
+																: ''
+														}
+														placeholder="home_lutron_set_credentials"
+														on={{
+															input: (event) =>
+																updateAllowedCapability(
+																	index,
+																	event.currentTarget.value,
+																),
+														}}
+														css={inputCss}
+													/>
+													<button
+														type="button"
+														on={{ click: () => removeAllowedCapability(index) }}
+														css={secondaryButtonCss}
+													>
+														Remove
+													</button>
+												</div>
+											),
+										)}
+									</div>
+									<div>
+										<button
+											type="button"
+											on={{ click: addAllowedCapability }}
+											css={secondaryButtonCss}
+										>
+											Add capability
+										</button>
+									</div>
+								</div>
+
 								{selectedSecret ? (
 									<div
 										css={{

diff --git a/packages/worker/migrations/0010-secret-allowed-capabilities.sql b/packages/worker/migrations/0010-secret-allowed-capabilities.sql
new file mode 100644
--- /dev/null
+++ b/packages/worker/migrations/0010-secret-allowed-capabilities.sql
@@ -1,0 +1,2 @@
+ALTER TABLE secret_entries
+ADD COLUMN allowed_capabilities TEXT NOT NULL DEFAULT '[]';

diff --git a/packages/worker/src/app/handlers/account-secrets.ts b/packages/worker/src/app/handlers/account-secrets.ts
--- a/packages/worker/src/app/handlers/account-secrets.ts
+++ b/packages/worker/src/app/handlers/account-secrets.ts
@@ -16,11 +16,13 @@
 	listSecrets,
 	resolveSecret,
 	saveSecret,
+	setSecretAllowedCapabilities,
 	setSecretAllowedHosts,
 } from '#mcp/secrets/service.ts'
 import { type SecretScope } from '#mcp/secrets/types.ts'
 import { listUiArtifactsByUserId } from '#mcp/ui-artifacts-repo.ts'
 import { type routes } from '#app/routes.ts'
+import { normalizeAllowedCapabilities } from '#mcp/secrets/allowed-capabilities.ts'
 import { normalizeAllowedHosts } from '#mcp/secrets/allowed-hosts.ts'
 
 type AccountEditableSecretScope = Extract<SecretScope, 'app' | 'user'>
@@ -39,6 +41,7 @@
 	appId: string | null
 	appTitle: string | null
 	allowedHosts: Array<string>
+	allowedCapabilities: Array<string>
 	createdAt: string
 	updatedAt: string
 	ttlMs: number | null
@@ -335,6 +338,7 @@
 		description: string
 		appId: string | null
 		allowedHosts: Array<string>
+		allowedCapabilities: Array<string>
 		createdAt: string
 		updatedAt: string
 		ttlMs: number | null
@@ -358,6 +362,7 @@
 		appId: secret.appId,
 		appTitle: secret.appId ? (appTitles.get(secret.appId) ?? null) : null,
 		allowedHosts: secret.allowedHosts,
+		allowedCapabilities: secret.allowedCapabilities,
 		createdAt: secret.createdAt,
 		updatedAt: secret.updatedAt,
 		ttlMs: secret.ttlMs,
@@ -446,6 +451,9 @@
 	const allowedHosts = normalizeAllowedHosts(
 		readStringArray(input.body, 'allowedHosts'),
 	)
+	const allowedCapabilities = normalizeAllowedCapabilities(
+		readStringArray(input.body, 'allowedCapabilities'),
+	)
 
 	if (!name) {
 		return jsonResponse({ ok: false, error: 'Secret name is required.' }, 400)
@@ -523,6 +531,17 @@
 				appId,
 			}),
 		})
+		await setSecretAllowedCapabilities({
+			env: input.env,
+			userId: input.user.mcpUser.userId,
+			name,
+			scope,
+			allowedCapabilities,
+			storageContext: getSecretContextForAccountSecret({
+				scope,
+				appId,
+			}),
+		})
 
 		if (currentSecret && currentSecret.id !== nextId) {
 			await deleteSecret({

diff --git a/packages/worker/src/app/saved-ui-hosted-html.ts b/packages/worker/src/app/saved-ui-hosted-html.ts
--- a/packages/worker/src/app/saved-ui-hosted-html.ts
+++ b/packages/worker/src/app/saved-ui-hosted-html.ts
@@ -469,6 +469,10 @@
 			(secret.app_id == null || typeof secret.app_id === 'string') &&
 			Array.isArray(secret.allowed_hosts) &&
 			secret.allowed_hosts.every((host) => typeof host === 'string') &&
+			Array.isArray(secret.allowed_capabilities) &&
+			secret.allowed_capabilities.every(
+				(capability) => typeof capability === 'string',
+			) &&
 			typeof secret.created_at === 'string' &&
 			typeof secret.updated_at === 'string' &&
 			(secret.ttl_ms == null ||

diff --git a/packages/worker/src/mcp/capabilities/secrets/secret-list.ts b/packages/worker/src/mcp/capabilities/secrets/secret-list.ts
--- a/packages/worker/src/mcp/capabilities/secrets/secret-list.ts
+++ b/packages/worker/src/mcp/capabilities/secrets/secret-list.ts
@@ -12,7 +12,7 @@
 	{
 		name: 'secret_list',
 		description:
-			'List available secret references for the signed-in user without revealing secret values. When scope is omitted, results include every accessible scope in precedence order. Use `codemode.secret_list({ scope })` inside execute-time code when you want the same metadata, including allowed hosts, from the sandbox.',
+			'List available secret references for the signed-in user without revealing secret values. When scope is omitted, results include every accessible scope in precedence order. Use `codemode.secret_list({ scope })` inside execute-time code when you want the same metadata, including allowed hosts and allowed capabilities, from the sandbox.',
 		keywords: ['secret', 'list', 'discovery', 'metadata', 'credentials'],
 		readOnly: true,
 		idempotent: true,
@@ -46,6 +46,7 @@
 					description: secret.description,
 					app_id: secret.appId,
 					allowed_hosts: secret.allowedHosts,
+					allowed_capabilities: secret.allowedCapabilities,
 					created_at: secret.createdAt,
 					updated_at: secret.updatedAt,
 					ttl_ms: secret.ttlMs,

diff --git a/packages/worker/src/mcp/capabilities/secrets/shared.ts b/packages/worker/src/mcp/capabilities/secrets/shared.ts
--- a/packages/worker/src/mcp/capabilities/secrets/shared.ts
+++ b/packages/worker/src/mcp/capabilities/secrets/shared.ts
@@ -7,6 +7,7 @@
 	description: z.string(),
 	app_id: z.string().nullable(),
 	allowed_hosts: z.array(z.string()),
+	allowed_capabilities: z.array(z.string()),
 	created_at: z.string(),
 	updated_at: z.string(),
 	ttl_ms: z.number().int().nonnegative().nullable(),

diff --git a/packages/worker/src/mcp/executor.node.test.ts b/packages/worker/src/mcp/executor.node.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/executor.node.test.ts
@@ -1,0 +1,54 @@
+import { expect, test } from 'vitest'
+import {
+	createCapabilitySecretAccessDeniedMessage,
+	createMissingSecretMessage,
+} from '#mcp/secrets/errors.ts'
+import { formatExecutionOutput, getExecutionErrorDetails } from './executor.ts'
+
+test('getExecutionErrorDetails returns concrete guidance for capability access denial', () => {
+	const error = new Error(
+		createCapabilitySecretAccessDeniedMessage(
+			'cloudflareToken',
+			'cloudflare_rest',
+		),
+	)
+
+	expect(getExecutionErrorDetails(error)).toEqual({
+		kind: 'secret_capability_access_required',
+		message:
+			'Secret "cloudflareToken" is not allowed for capability "cloudflare_rest". If this capability should be able to use the secret, ask the user whether to add "cloudflare_rest" to the secret\'s allowed capabilities in the account secrets UI, then retry after they approve that policy change.',
+		nextStep:
+			"Ask the user whether this capability should be allowed to use the secret. If they approve, help them add this capability name to the secret's allowed capabilities in the account secrets UI, then retry.",
+		secretNames: ['cloudflareToken'],
+		capabilityName: 'cloudflare_rest',
+		suggestedAction: {
+			type: 'edit_secret_policy',
+			policyField: 'allowed_capabilities',
+		},
+	})
+})
+
+test('formatExecutionOutput includes capability access next step', () => {
+	const result = {
+		error: new Error(
+			createCapabilitySecretAccessDeniedMessage(
+				'cloudflareToken',
+				'cloudflare_rest',
+			),
+		),
+	} as const
+
+	expect(formatExecutionOutput(result)).toContain(
+		"Next step: Ask the user whether this capability should be allowed to use the secret. If they approve, help them add this capability name to the secret's allowed capabilities in the account secrets UI, then retry.",
+	)
+})
+
+test('formatExecutionOutput keeps missing secret guidance intact', () => {
+	const result = {
+		error: new Error(createMissingSecretMessage('missingToken')),
+	} as const
+
+	expect(formatExecutionOutput(result)).toContain(
+		'Open a generated UI so the user can provide and save this secret',
+	)
+})

diff --git a/packages/worker/src/mcp/executor.ts b/packages/worker/src/mcp/executor.ts
--- a/packages/worker/src/mcp/executor.ts
+++ b/packages/worker/src/mcp/executor.ts
@@ -4,6 +4,7 @@
 import { type FetchGatewayProps } from '#mcp/fetch-gateway.ts'
 import {
 	isSecretAuthRequiredMessage,
+	parseCapabilityAccessRequiredMessage,
 	parseHostApprovalRequiredMessage,
 	parseMissingSecretMessage,
 } from '#mcp/secrets/errors.ts'
@@ -45,6 +46,17 @@
 			}
 	  }
 	| {
+			kind: 'secret_capability_access_required'
+			message: string
+			nextStep: string
+			secretNames: Array<string>
+			capabilityName: string
+			suggestedAction: {
+				type: 'edit_secret_policy'
+				policyField: 'allowed_capabilities'
+			}
+	  }
+	| {
 			kind: 'secret_required'
 			message: string
 			nextStep: string
@@ -84,6 +96,22 @@
 		}
 	}
 
+	const capabilityAccessDetails = parseCapabilityAccessRequiredMessage(message)
+	if (capabilityAccessDetails) {
+		return {
+			kind: 'secret_capability_access_required',
+			message,
+			nextStep:
+				"Ask the user whether this capability should be allowed to use the secret. If they approve, help them add this capability name to the secret's allowed capabilities in the account secrets UI, then retry.",
+			secretNames: [capabilityAccessDetails.secretName],
+			capabilityName: capabilityAccessDetails.capabilityName,
+			suggestedAction: {
+				type: 'edit_secret_policy',
+				policyField: 'allowed_capabilities',
+			},
+		}
+	}
+
 	const missingSecretDetails = parseMissingSecretMessage(message)
 	if (missingSecretDetails) {
 		return {

diff --git a/packages/worker/src/mcp/generated-ui-api.ts b/packages/worker/src/mcp/generated-ui-api.ts
--- a/packages/worker/src/mcp/generated-ui-api.ts
+++ b/packages/worker/src/mcp/generated-ui-api.ts
@@ -299,6 +299,7 @@
 						description: secret.description,
 						app_id: secret.appId,
 						allowed_hosts: secret.allowedHosts,
+						allowed_capabilities: secret.allowedCapabilities,
 						created_at: secret.createdAt,
 						updated_at: secret.updatedAt,
 						ttl_ms: secret.ttlMs,
@@ -338,6 +339,7 @@
 						description: saved.description,
 						app_id: saved.appId,
 						allowed_hosts: saved.allowedHosts,
+						allowed_capabilities: saved.allowedCapabilities,
 						created_at: saved.createdAt,
 						updated_at: saved.updatedAt,
 						ttl_ms: saved.ttlMs,

diff --git a/packages/worker/src/mcp/index.ts b/packages/worker/src/mcp/index.ts
--- a/packages/worker/src/mcp/index.ts
+++ b/packages/worker/src/mcp/index.ts
@@ -80,10 +80,10 @@
 - Each capability call returns that capability's raw structured result value.
 - When chaining calls, read fields from the previous result using its outputSchema.
 - Chain multiple calls, use conditionals, and return structured results.
-- Use \`await codemode.secret_list({})\` or \`await codemode.secret_list({ scope: 'app' })\` when you need secret metadata such as names, descriptions, scopes, and allowed hosts from the sandbox.
+- Use \`await codemode.secret_list({})\` or \`await codemode.secret_list({ scope: 'app' })\` when you need secret metadata such as names, descriptions, scopes, allowed hosts, and allowed capabilities from the sandbox.
 - Use \`await codemode.value_get({ name })\` or \`await codemode.value_list({ scope })\` for readable non-secret configuration that generated UI code should be able to store and read back later.
 - Use normal \`fetch(...)\` for outbound HTTP. To inject a stored secret, place a placeholder such as \`{{secret:cloudflareToken}}\` or \`{{secret:cloudflareToken|scope=user}}\` in the URL, headers, or request body; the host resolves it server-side and blocks unapproved destinations.
-- Some capability input fields also accept secret placeholders. When an input schema marks a string field with \`x-kody-secret: true\`, you may pass \`{{secret:name}}\` or \`{{secret:name|scope=user}}\` there instead of a raw value.
+- Some capability input fields also accept secret placeholders. When an input schema marks a string field with \`x-kody-secret: true\`, you may pass \`{{secret:name}}\` or \`{{secret:name|scope=user}}\` there instead of a raw value. If that secret has an allowed-capabilities policy, the current capability name must be on the allowlist.
 - Secret placeholders are not general-purpose string interpolation. Do not use \`execute\` to build a string or object that merely returns \`{{secret:...}}\`; those placeholders only resolve in secret-aware fetch paths or capability inputs that explicitly opt into \`x-kody-secret\`.
 - Saving or updating a secret does not authorize sending it anywhere. If a fetch fails because a host is not approved for that secret, ask the user whether to open the approval link and approve that host in the web app.
 - Secrets are intentionally not readable or updatable through \`codemode\`. Never ask the user to paste a secret into chat; use generated UI flows such as \`saveSecret(...)\` when the user needs to provide or rotate a value, and use \`codemode.secret_delete(...)\` only when removing a stored secret reference.

diff --git a/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts b/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
--- a/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
+++ b/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
@@ -1337,6 +1337,7 @@
 		description: 'Session-only verification code',
 		app_id: null,
 		allowed_hosts: [],
+		allowed_capabilities: [],
 		created_at: expect.any(String),
 		updated_at: expect.any(String),
 		ttl_ms: expect.any(Number),
@@ -1401,6 +1402,7 @@
 			description: 'App-scoped Cloudflare deployment token',
 			app_id: appId,
 			allowed_hosts: [],
+			allowed_capabilities: [],
 			created_at: expect.any(String),
 			updated_at: expect.any(String),
 			ttl_ms: null,

diff --git a/packages/worker/src/mcp/run-codemode-registry.node.test.ts b/packages/worker/src/mcp/run-codemode-registry.node.test.ts
--- a/packages/worker/src/mcp/run-codemode-registry.node.test.ts
+++ b/packages/worker/src/mcp/run-codemode-registry.node.test.ts
@@ -1,6 +1,7 @@
-import { expect, test } from 'vitest'
+import { expect, test, vi } from 'vitest'
 import { createMcpCallerContext } from '#mcp/context.ts'
 import { buildCodemodeFns } from './run-codemode-registry.ts'
+import * as secretService from '#mcp/secrets/service.ts'
 
 test('buildCodemodeFns resolves annotated home capability secret placeholders', async () => {
 	let toolArguments: Record<string, unknown> | null = null
@@ -72,10 +73,12 @@
 		env,
 		createMcpCallerContext({
 			baseUrl: 'https://heykody.dev',
+			user: { userId: 'user-123' },
 			homeConnectorId: 'default',
 		}),
 		{
-			resolveSecretValue: async (secret) => `${secret.name}-resolved`,
+			resolveSecretValue: async (secret, capabilityName) =>
+				`${secret.name}-${capabilityName}-resolved`,
 		},
 	)
 
@@ -87,7 +90,93 @@
 
 	expect(toolArguments).toEqual({
 		processorId: 'lutron-192-168-0-41',
-		username: 'lutronUsername-resolved',
-		password: 'lutronPassword-resolved',
+		username: 'lutronUsername-home_lutron_set_credentials-resolved',
+		password: 'lutronPassword-home_lutron_set_credentials-resolved',
 	})
 })
+
+test('buildCodemodeFns denies capability secret placeholders for disallowed capabilities', async () => {
+	const resolveSecretSpy = vi
+		.spyOn(secretService, 'resolveSecret')
+		.mockResolvedValue({
+			found: true,
+			value: 'lutronUsername-resolved',
+			scope: 'user',
+			allowedHosts: [],
+			allowedCapabilities: ['some_other_capability'],
+		})
+	const env = {
+		HOME_CONNECTOR_SESSION: {
+			idFromName(name: string) {
+				return name
+			},
+			get() {
+				return {
+					async fetch(input: string | URL | Request) {
+						const url = new URL(
+							typeof input === 'string'
+								? input
+								: input instanceof URL
+									? input.toString()
+									: input.url,
+						)
+						if (url.pathname.endsWith('/snapshot')) {
+							return Response.json({
+								connectorId: 'default',
+								connectedAt: '2026-03-27T00:00:00.000Z',
+								lastSeenAt: '2026-03-27T00:00:01.000Z',
+								tools: [
+									{
+										name: 'lutron_set_credentials',
... diff truncated: showing 800 of 1379 lines
Open in Web Open in Cursor 


Use this for capabilities that need to accept a secret value as an argument but
are not themselves the host-approval boundary. Good fits include:

Expand Down Expand Up @@ -284,6 +289,8 @@ scope narrow:

- annotate only the exact credential fields, not the whole object
- prefer this for local persistence or device-side credential flows
- tell users which capability names should be added to a secret's
`allowed_capabilities` policy when a workflow depends on restricted secrets
- avoid using it for generic remote API wrappers where fetch-time host approval
should remain the enforcement point

Expand All @@ -295,8 +302,8 @@ Public MCP behavior should be verified through the compact tool surface:
ranked results
- use `execute` to confirm the capability runs correctly

Prefer E2E tests in `packages/worker/src/mcp/*.mcp-e2e.test.ts` for the real
MCP contract.
Prefer E2E tests in `packages/worker/src/mcp/*.mcp-e2e.test.ts` for the real MCP
contract.

Registry invariants (duplicate capability names, domain/capability mismatches,
duplicate domain registration) are covered in
Expand Down
29 changes: 22 additions & 7 deletions docs/agents/secret-host-approval.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,19 @@ secrets.

## Rule

Allowed outbound hosts for a secret are privileged policy, not normal secret
Allowed outbound hosts for a secret and allowed capabilities for direct
capability-input secret resolution are privileged policy, not normal secret
metadata.

That policy must not be created, widened, or modified by:
Those policies must not be created, widened, or modified by:

- MCP tools
- execute-time sandboxed code
- generated UI code
- capability handlers that serve agent-driven secret creation or update flows

Allowed outbound hosts may only be changed through the authenticated account
admin UI approval flow.
Allowed outbound hosts and allowed capabilities may only be changed through the
authenticated account admin UI.

In this repo, that means the user must approve host access through the account
secrets experience, such as `/account/secrets` and the focused approval route at
Expand All @@ -29,7 +30,7 @@ allowlist unless the user has already approved one or more hosts in the admin
UI.

Saving or updating a secret value does not authorize sending that secret to any
host.
host or passing it into any capability.

If an outbound request uses a placeholder such as `{{secret:name}}` and the
target host is not already approved for that secret, the correct behavior is:
Expand All @@ -42,16 +43,22 @@ target host is not already approved for that secret, the correct behavior is:
## What agents must not do

Do not design or document any MCP capability, generated UI helper, or client
library that allows agent-controlled writes to a secret's allowed hosts.
library that allows agent-controlled writes to a secret's allowed hosts or
allowed capabilities.

Specifically, do not:

- add `allowed_hosts` or equivalent fields to MCP-facing secret create/update
inputs
- add `allowed_capabilities` or equivalent fields to MCP-facing secret
create/update inputs
- imply that a generated UI can self-authorize a host just because it can save a
secret
- imply that execute-time capability calls can widen which capabilities may
consume a secret
- imply that execute-time code can widen egress permissions
- treat host approval as ordinary secret metadata editing
- treat host approval or capability allowlists as ordinary secret metadata
editing

If a workflow would be smoother by auto-approving a host, the fix should be
better guidance, helper APIs, or UX around the approval flow, not a new write
Expand All @@ -62,7 +69,10 @@ path that bypasses the admin UI.
When writing capability descriptions or agent-facing docs:

- say explicitly that secret save/update does not grant outbound use
- say explicitly that secret save/update does not grant capability access
- say explicitly that only the authenticated account admin UI can approve hosts
- say explicitly that only the authenticated account admin UI can restrict which
capabilities may consume a secret directly
- tell agents to inspect secret metadata before making a secret-bearing request
- tell agents to surface the approval link and stop on deny

Expand All @@ -84,6 +94,9 @@ That feature is for cases where the capability needs the secret value itself,
for example to store credentials on a local connector or pass them into a
device-local action.

If a secret has an allowed-capabilities policy, Kody enforces that allowlist by
capability name before resolving the placeholder for the handler.

Use it narrowly:

- mark only the exact sensitive fields
Expand All @@ -105,11 +118,13 @@ Generated UIs may:
- save those values as secrets
- save and read back non-secret values for public configuration
- inspect secret metadata, including current allowed hosts
- inspect secret metadata, including current allowed capabilities
- present approval links returned from blocked requests

Generated UIs may not:

- set allowed hosts directly
- set allowed capabilities directly
- bypass the admin approval route
- silently retry secret-bearing requests after a deny
- use `executeCode(...)` as a general string interpolation mechanism for
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,6 @@ test('readSavedAppSourceFromHostToolResult preserves host tool errors', () => {
errorMessage: 'Saved app not found for this user.',
})
})

test('buildLocalMessageLogRuntimeSource logs sendMessage locally outside hosted contexts', () => {
const originalWindow = globalThis.window
const originalDocument = globalThis.document
Expand Down
5 changes: 5 additions & 0 deletions packages/worker/client/mcp-apps/generated-ui-shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@
description: string
app_id: string | null
allowed_hosts: Array<string>
allowed_capabilities: Array<string>
created_at: string
updated_at: string
ttl_ms: number | null
}

type ValueMetadata = {

Check warning on line 31 in packages/worker/client/mcp-apps/generated-ui-shell.ts

View workflow job for this annotation

GitHub Actions / 🧹 Lint

eslint(no-unused-vars)

Type alias 'ValueMetadata' is declared but never used.
name: string
scope: ValueScope
value: string
Expand Down Expand Up @@ -772,6 +773,10 @@
(secret.app_id == null || typeof secret.app_id === 'string') &&
Array.isArray(secret.allowed_hosts) &&
secret.allowed_hosts.every((host) => typeof host === 'string') &&
Array.isArray(secret.allowed_capabilities) &&
secret.allowed_capabilities.every(
(capability) => typeof capability === 'string',
) &&
typeof secret.created_at === 'string' &&
typeof secret.updated_at === 'string' &&
(secret.ttl_ms == null ||
Expand Down
Loading
Loading