Skip to content

Expose skill permission grants to SDK hosts before activation #509

Open

Description

@superbiche

Request

Please document a supported way to inspect a selected skill's permission grants
before activating it, or consider typed grant metadata for SDK hosts. In the
tested version, approving a model's Skill request exposes only the skill ID
and description. It does not disclose that the skill will pre-approve Write.
A slash invocation activates that grant without a canUseTool callback.

This is a capability/disclosure request. The
documented permission order
allows earlier approvals to skip canUseTool; registering that callback alone
does not make it the sole permission authority. The reproduction below confirms
the behavior, rather than asserting a violation of that documented contract.

Environment

  • @anthropic-ai/claude-agent-sdk 0.3.293
  • Native Claude Code 2.1.299 selected through pathToClaudeCodeExecutable
  • Node 26.10.0, Linux x64
  • permissionMode: "default", allowDangerouslySkipPermissions: false
  • Isolated HOME/config/project, empty user settings, no real credentials
  • Direct SDK query() only; no acpx, ACP client, or ACP adapter
  • Deterministic HTTP fixture bound to loopback; no external model needed

Reproduction and results

The skill contains:

---
name: probe
description: Synthetic permission fixture
allowed-tools: Write
---
Use Write to create the requested file.

The callback denies every tool, except Skill in the approve-Skill-only cases.
The loopback server returns Skill, then Write, then completion; for slash
invocations it returns Write, then completion. The actual native Write tool
must create the marker for a row to count as written.

Source Invocation Host callback policy Callback tools Marker written
plugin, grant model deny all Skill, Write no
plugin, grant model approve Skill only Skill yes
plugin, grant slash deny all none yes
user directory, grant model approve Skill only Skill yes
user directory, grant slash deny all none yes
plugin, no grant model approve Skill only Write no
plugin, no grant slash deny all Write no
user directory, no grant model approve Skill only Write no
user directory, no grant slash deny all Write no
plugin, grant; PreToolUse denies Write slash deny all none no
plugin, grant; managed-rules-only slash deny all none yes
user directory, grant; managed-rules-only slash deny all Write no

The recorded grant-bearing model invocation exposes this callback data:

{"toolName":"Skill","input":{"skill":"p:probe"},"description":"Synthetic permission fixture"}

decisionReason is absent; no granted-tool list is present. In the no-grant
cases native Skill activation itself does not require this callback.

Documented behavior versus the requested metadata

The SDK skill documentation
already documents project/personal skill pre-approval in SDK sessions. The
native skill documentation
explains that a skill's tool grant lasts for the invoking turn.
The managed-only setting reference
defines which grant sources are ignored; the
published SDK 0.3.293 declaration
explicitly retains grants for host-delivered --plugin-dir plugins.
The managed-plugin row therefore matches a documented trusted-host exception;
it is not a demonstrated managed-policy bypass.

The missing capability requested here is the granted-tool list in the Skill
callback payload and a supported inspection path before activation, including
user slash activation. Neither the documented approval order nor the existing
mitigation supplies that disclosure metadata in the observed callback.

Existing mitigations and limits

A denying PreToolUse hook blocks the demonstrated write even when the skill
grants Write. Removing the grant metadata also restores the Write callback;
withholding the skill is not the only mitigation. These approaches have
different purposes: the hook preserves the installed skill, while stripping
its metadata changes its grant behavior.

allowManagedPermissionRulesOnly blocks the tested user-directory grant but
does not block the host-delivered plugin grant. Do not generalize that result
to every settings source or plugin feature. Skill hooks and agent
permissionMode are not reproduced by this fixture.

Desired capability

A host should be able to learn the grants of the selected skill before model
activation and before a user slash activation. Possible outcomes include a
supported inspection API or structured activation metadata. Such metadata
would improve disclosure; it would not replace PreToolUse for enforcing a
policy across every call.

If an inspection path already exists, a documented example covering both
plugin-qualified and user-directory skills would resolve this request.

Related reports

  • #502 asks for no-model access to a selected skill's complete body under Query permissions. This request concerns grant metadata and activation disclosure.
  • #19 concerns allowedTools versus tool availability, not skill activation disclosure.
  • #422 reports a different tool's PreToolUse behavior; the Write-hook control here succeeds.
  • claude-code #18737 is related closed documentation history about skill grants in SDK sessions; it does not request the activation metadata above.

Runnable fixture

Save the following as repro.mjs beside an existing installation of SDK
0.3.293. Set CLAUDE_FIXTURE_EXECUTABLE to the native Claude Code 2.1.299
executable; SDK_MODULE_PATH can select an existing sdk.mjs if normal Node
resolution is unavailable. Run node repro.mjs. The script installs nothing
and needs no external model or credentials. It asserts the marker state of
all 12 rows, successful SDK completion and the negative controls. Callback
lists and callback payloads are recorded; their exact contents are not all
asserted by the script.

Self-contained SDK-only fixture
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

// No ACP client/adapter, external model, or real credentials. SDK_MODULE_PATH
// optionally selects an already-installed sdk.mjs; otherwise use normal resolution.
const modulePath = process.env.SDK_MODULE_PATH;
const executable = process.env.CLAUDE_FIXTURE_EXECUTABLE;
const { query } = await import(modulePath ? pathToFileURL(modulePath).href : '@anthropic-ai/claude-agent-sdk');
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sdk-skill-permissions-'));
const output = path.resolve(process.env.FIXTURE_OUTPUT || path.join(root, 'results.json'));
const originalPath = process.env.PATH;
// Eliminate ambient credentials/configuration from the SDK parent as well as child.
for (const key of Object.keys(process.env)) delete process.env[key];
Object.assign(process.env, { HOME: root, PATH: originalPath, LANG: 'C.UTF-8' });

const scenarios = [
  { id: 'plugin-model-deny-all', source: 'plugin', grant: true, slash: false, approveSkill: false, written: false },
  { id: 'plugin-model-approve-skill', source: 'plugin', grant: true, slash: false, approveSkill: true, written: true },
  { id: 'plugin-slash-deny-all', source: 'plugin', grant: true, slash: true, approveSkill: false, written: true },
  { id: 'user-model-approve-skill', source: 'user', grant: true, slash: false, approveSkill: true, written: true },
  { id: 'user-slash-deny-all', source: 'user', grant: true, slash: true, approveSkill: false, written: true },
  { id: 'control-plugin-model', source: 'plugin', grant: false, slash: false, approveSkill: true, written: false },
  { id: 'control-plugin-slash', source: 'plugin', grant: false, slash: true, approveSkill: false, written: false },
  { id: 'control-user-model', source: 'user', grant: false, slash: false, approveSkill: true, written: false },
  { id: 'control-user-slash', source: 'user', grant: false, slash: true, approveSkill: false, written: false },
  { id: 'mitigation-pre-tool-use', source: 'plugin', grant: true, slash: true, approveSkill: false, hook: true, written: false },
  { id: 'managed-plugin-slash', source: 'plugin', grant: true, slash: true, approveSkill: false, managed: true, written: true },
  { id: 'managed-user-slash', source: 'user', grant: true, slash: true, approveSkill: false, managed: true, written: false },
];

function reply(res, body, content, index) {
  const stop = content.type === 'tool_use' ? 'tool_use' : 'end_turn';
  const message = { id: `msg_fixture_${index}`, type: 'message', role: 'assistant', model: body.model, content: [content], stop_reason: stop, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 5 } };
  if (!body.stream) {
    res.writeHead(200, { 'content-type': 'application/json' });
    res.end(JSON.stringify(message));
    return;
  }
  res.writeHead(200, { 'content-type': 'text/event-stream' });
  const isTool = content.type === 'tool_use';
  const events = [
    ['message_start', { type: 'message_start', message: { ...message, content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } }],
    ['content_block_start', { type: 'content_block_start', index: 0, content_block: isTool ? { type: 'tool_use', id: content.id, name: content.name, input: {} } : { type: 'text', text: '' } }],
    ['content_block_delta', { type: 'content_block_delta', index: 0, delta: isTool ? { type: 'input_json_delta', partial_json: JSON.stringify(content.input) } : { type: 'text_delta', text: content.text } }],
    ['content_block_stop', { type: 'content_block_stop', index: 0 }],
    ['message_delta', { type: 'message_delta', delta: { stop_reason: stop, stop_sequence: null }, usage: { output_tokens: 5 } }],
    ['message_stop', { type: 'message_stop' }],
  ];
  for (const [event, data] of events) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
  res.end();
}

async function run(scenario) {
  const dir = path.join(root, scenario.id);
  const home = path.join(dir, 'home');
  const cwd = path.join(dir, 'project');
  const plugin = path.join(dir, 'plugin');
  const marker = path.join(cwd, 'marker.txt');
  for (const p of [home, cwd, path.join(home, '.claude')]) fs.mkdirSync(p, { recursive: true });
  fs.writeFileSync(path.join(home, '.claude/settings.json'), '{}\n');
  const skillDir = scenario.source === 'plugin' ? path.join(plugin, 'skills/probe') : path.join(home, '.claude/skills/probe');
  fs.mkdirSync(skillDir, { recursive: true });
  fs.writeFileSync(path.join(skillDir, 'SKILL.md'), `---\nname: probe\ndescription: Synthetic permission fixture\n${scenario.grant ? 'allowed-tools: Write\n' : ''}---\nUse Write to create the requested file.\n`);
  if (scenario.source === 'plugin') {
    fs.mkdirSync(path.join(plugin, '.claude-plugin'));
    fs.writeFileSync(path.join(plugin, '.claude-plugin/plugin.json'), JSON.stringify({ name: 'p', version: '1.0.0' }));
  }
  const skill = scenario.source === 'plugin' ? 'p:probe' : 'probe';
  const calls = [], hookCalls = [], modelRequests = [], messages = [];
  let stderr = '';
  const server = http.createServer(async (req, res) => {
    try {
      let raw = '';
      for await (const chunk of req) raw += chunk;
      const body = raw ? JSON.parse(raw) : {};
      if (!req.url.includes('/messages') || req.url.includes('count_tokens')) {
        res.writeHead(200, { 'content-type': 'application/json' });
        res.end(JSON.stringify(req.url.includes('count_tokens') ? { input_tokens: 10 } : {}));
        return;
      }
      const main = body.tools?.some(tool => tool.name === 'Write');
      if (!main) { reply(res, body, { type: 'text', text: 'fixture auxiliary response' }, 0); return; }
      const used = body.messages.flatMap(message => Array.isArray(message.content) ? message.content : []).filter(block => block.type === 'tool_use').map(block => block.name);
      const next = !scenario.slash && !used.includes('Skill') ? 'Skill' : !used.includes('Write') ? 'Write' : undefined;
      modelRequests.push({ used, next: next || 'text', advertisedTools: body.tools.map(tool => tool.name) });
      const input = next === 'Skill' ? { skill } : { file_path: marker, content: 'SYNTHETIC_FIXTURE_MARKER\n' };
      reply(res, body, next ? { type: 'tool_use', id: `tool_fixture_${modelRequests.length}`, name: next, input } : { type: 'text', text: 'fixture complete' }, modelRequests.length);
    } catch (error) { res.writeHead(500); res.end(String(error)); }
  });
  await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  const base = `http://127.0.0.1:${server.address().port}`;
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 60000);
  const env = {
    HOME: home, PATH: originalPath, LANG: 'C.UTF-8', CLAUDE_CONFIG_DIR: path.join(home, '.claude'),
    XDG_CONFIG_HOME: path.join(home, '.config'), ANTHROPIC_BASE_URL: base,
    ANTHROPIC_API_KEY: 'synthetic-loopback-key-not-a-credential',
    CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1',
  };
  const options = {
    cwd, env, settingSources: scenario.source === 'user' ? ['user'] : [],
    permissionMode: 'default', allowDangerouslySkipPermissions: false,
    model: 'claude-sonnet-4-6', maxTurns: 5, abortController: controller,
    ...(executable ? { pathToClaudeCodeExecutable: executable } : {}),
    ...(scenario.source === 'plugin' ? { plugins: [{ type: 'local', path: plugin }] } : {}),
    ...(scenario.managed ? { managedSettings: { allowManagedPermissionRulesOnly: true } } : {}),
    ...(scenario.hook ? { hooks: { PreToolUse: [{ matcher: 'Write', hooks: [async input => {
      hookCalls.push({ tool: input.tool_name });
      return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'fixture host denies writes' } };
    }] }] } } : {}),
    canUseTool: async (toolName, input, metadata) => {
      calls.push({ toolName, input, description: metadata.description, decisionReason: metadata.decisionReason });
      return scenario.approveSkill && toolName === 'Skill' ? { behavior: 'allow', updatedInput: input } : { behavior: 'deny', message: 'fixture host denies tool' };
    },
    stderr: text => { stderr += text; },
  };
  let error;
  const q = query({ prompt: scenario.slash ? `/${skill} create ${marker}` : `Use the ${skill} skill to create ${marker}`, options });
  try {
    for await (const message of q) {
      messages.push({ type: message.type, subtype: message.subtype, ...(message.type === 'result' ? { is_error: message.is_error, errors: message.errors } : {}) });
    }
  } catch (e) { error = String(e); }
  finally {
    clearTimeout(timer);
    q.close();
    await new Promise(resolve => server.close(resolve));
    server.closeAllConnections();
  }
  return { id: scenario.id, source: scenario.source, grant: scenario.grant, slash: scenario.slash, managed: !!scenario.managed, hook: !!scenario.hook, expectedWritten: scenario.written, written: fs.existsSync(marker), calls, hookCalls, modelRequests, messages, ...(error ? { error } : {}), ...(stderr ? { stderr } : {}) };
}

const results = [];
for (const scenario of scenarios) {
  const result = await run(scenario);
  results.push(result);
  fs.mkdirSync(path.dirname(output), { recursive: true });
  fs.writeFileSync(output, JSON.stringify({ root, results }, null, 2) + '\n');
  console.log(JSON.stringify({ id: result.id, written: result.written, calls: result.calls.map(x => x.toolName), hookCalls: result.hookCalls, error: result.error }));
}
for (const result of results) {
  assert.equal(result.error, undefined, `${result.id}: SDK failed`);
  assert.ok(result.modelRequests.length >= 2, `${result.id}: fixture must exercise tool requests`);
  assert.equal(result.written, result.expectedWritten, `${result.id}: unexpected marker state`);
  assert.ok(result.messages.some(message => message.type === 'result' && !message.is_error), `${result.id}: successful SDK result missing`);
  if (result.written) assert.ok(!result.calls.some(call => call.toolName === 'Write'), `${result.id}: Write unexpectedly reached callback`);
  if (!result.grant) assert.ok(result.calls.some(call => call.toolName === 'Write'), `${result.id}: no-grant control did not reach callback`);
  if (result.hook) assert.equal(result.hookCalls.length, 1, 'PreToolUse denial must execute');
}
console.log(`PASS: ${results.length} SDK-only loopback cases; results: ${output}`);

@superbiche · user · drafted with GPT-6.1 Sol, reviewed before posting; the voice and decisions are mine.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationenhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions