Extending the Agent โ€” Skills, Plugins, and MCP

Lesson 7: Extending the Agent โ€” Skills, Plugins, and MCP

Tools give the agent actions. The three mechanisms in this lesson give it procedures (skills), distribution (plugins), and connections (MCP servers). Together they are how one codebase serves many teams, tenants, and external systems without forking the agent.

Skills: procedural knowledge as files

A skill is a markdown document of instructions the agent loads on demand. Where a tool describes what it can do, a skill describes how this organisation does it โ€” review standards, migration checklists, release procedures. The value is progressive disclosure: the full text is not in every prompt, only when relevant.

skills/
โ”œโ”€โ”€ code-review/
โ”‚   โ””โ”€โ”€ SKILL.md
โ””โ”€โ”€ documentation/
    โ””โ”€โ”€ SKILL.md
---
name: code-review
description: Specialized code review capabilities
---

# Code Review Guidelines

When reviewing code, always check for:

1. **Security vulnerabilities** - SQL injection, XSS, etc.
2. **Performance issues** - N+1 queries, memory leaks
3. **Code style** - Consistent formatting, naming conventions
4. **Test coverage** - Are critical paths tested?

Provide specific line-number references and suggested fixes.
Frontmatter fieldPurpose
nameThe skill's identifier โ€” used by disabledSkills to disable it selectively. If omitted, the directory name is used.
descriptionWhat the skill does. This is what the model sees when deciding whether to load it.

The body is the payload: it is injected into session context when the skill is loaded.

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({
  model: "gpt-5.4",
  skillDirectories: ["./skills/code-review", "./skills/documentation"],
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

await session.sendAndWait({ prompt: "Review this code for security issues" });
Two directory forms, and both are valid. Discovery treats a directory that directly contains a SKILL.md as a skill bundle, and otherwise recursively discovers topmost bundles. So a single skill directory (./skills/code-review) and a parent directory whose immediate subdirectories are skills (./skills) both work. If a skill mysteriously fails to load, try the other form before assuming a bug โ€” and remember discovery is immediate subdirectories only, not an unbounded crawl, unless the recursive bundle rule applies.

Four lists, not one: the discovery surface

Skills are one of four discoverable customization types, and the SDK accepts all four as session options:

const session = await client.createSession({
  skillDirectories: ["./skills"],
  agentDirectories: ["./agents"],
  instructionDirectories: ["./instructions"],
  hookDirectories: ["./hooks"],
});

TypeScript and Java use these camelCase names; Python and Rust use snake case; Go and .NET use Pascal case. The same four lists are accepted on create, resume, and option updates, and the semantics have real edges:

BehaviourDetail
SDK paths may live outside the checkoutUnlike repository-declared paths, which must resolve inside the declaring checkout
Relative paths resolve onceAgainst the request's effective working directory. Changing the working directory later does not move retained roots.
Empty list vs omittedAn empty list clears only the explicit SDK contribution; omission or null leaves it unchanged on update
Directory inputs are discovery config, not filesystem grantsThey do not widen additionalDirectories; existing hook sandbox rules still apply
Failed hookDirectories replacementThe previous directory option and live hook service remain in place โ€” a failed update never leaves you with no hooks

There is a second, repository-scoped surface โ€” .github/copilot/settings.json โ€” for versioned content that ships in packages, submodules, or vendored directories:

{
  "skillDirectories": ["node_modules/@example/team/skills"],
  "agentDirectories": ["vendor/team/agents"],
  "instructionDirectories": ["vendor/team/instructions"],
  "hookDirectories": ["vendor/team/hooks"]
}

Precedence notes worth internalising: a key in .github/copilot/settings.local.json replaces only that repository list (an empty list removes its contribution, omitted keys inherit the checked-in list), and repository lists never replace SDK inputs or existing user skill directories. Repository paths must be nonempty literal directories inside the checkout โ€” absolute paths, ~ or env-var expansion, globs, and escapes are rejected. Symlinks are allowed only if their resolved roots and discovered descendants stay inside. And listing a location does not enable a disabled customization type or grant filesystem access โ€” those are separate switches.

Per-agent skills, and the inheritance rule

const session = await client.createSession({
  skillDirectories: ["./skills"],
  customAgents: [
    {
      name: "security-auditor",
      description: "Security-focused code reviewer",
      prompt: "Focus on OWASP Top 10 vulnerabilities",
      skills: ["security-scan", "dependency-check"],
    },
    {
      name: "docs-writer",
      description: "Technical documentation writer",
      prompt: "Write clear, concise documentation",
      skills: ["markdown-lint"],
    },
  ],
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});
Skills are opt-in and do not inherit. An agent with a skills list gets the full content of each listed skill eagerly injected at startup โ€” it never needs to invoke a skill tool, because the instructions are already there. An agent without a skills field receives no skill content at all, and sub-agents do not inherit skills from the parent session. Skill names resolve from the session-level skillDirectories. This is deliberate: eager injection costs tokens, so you choose per agent.

Disabling, reloading, and provider-served skills

const session = await client.createSession({
  skillDirectories: ["./skills"],
  disabledSkills: ["markdown-lint"],     // selectively off
  onPermissionRequest: approveAll,
});

// Pick up on-disk changes without restarting
await session.rpc.skills.reload();

For multi-tenant services, skills often live in a database rather than on disk. Skill providers (experimental โ€” the API can change) serve them from your own storage. A provider implements exactly two operations:

OperationReturnsCalled
List skillsCatalog metadata per skill: name, description, and optionally userInvocable, disableModelInvocation, argumentHintWhen the runtime loads the session's skills
Read skillThe markdown for one skill, or a not-found resultOnly when that skill is actually loaded

Provider skills join the session catalog alongside file-based skills, and the model loads them on demand through the skill tool. Note the trust posture: provider content is your content served over your own transport, so your provider is responsible for its integrity.

Plugins: the distribution unit

A plugin is a directory that bundles any combination of skills, hooks, MCP servers, agents, and LSP configuration behind one manifest. It is how you ship a capability set โ€” to a team, or into a product image โ€” as a versioned artifact rather than a pile of configuration.

my-plugin/
โ”œโ”€โ”€ plugin.json              # manifest (required unless SKILL.md only)
โ”œโ”€โ”€ SKILL.md                 # optional: top-level skill
โ”œโ”€โ”€ hooks.json               # optional: hooks config
โ”œโ”€โ”€ .mcp.json                # optional: MCP server config
โ”œโ”€โ”€ agents/                  # optional: custom agents (one .md per agent)
โ”‚   โ””โ”€โ”€ code-reviewer.md
โ””โ”€โ”€ skills/                  # optional: additional skills
    โ””โ”€โ”€ lint-fix/
        โ””โ”€โ”€ SKILL.md

The CLI scans each plugin directory for a plugin.json manifest or a root-level SKILL.md. The manifest may alternatively live at .github/plugin.json or .github/plugin/plugin.json, so a plugin can sit inside an existing repository without changing its root layout. Every subsystem has its own loader and is optional โ€” a plugin only needs the parts it contributes.

import { CopilotClient, RuntimeConnection } from "@github/copilot-sdk";

const client = new CopilotClient({
  connection: RuntimeConnection.forStdio({
    args: [
      "--plugin-dir", "./plugins/code-reviewer",
      "--plugin-dir", "./plugins/lint-fix",
    ],
  }),
});

await client.start();
Two plugin traps, both silent. (1) --plugin-dir is only forwarded when the SDK spawns the CLI. Connecting with fromUri means your extra args go nowhere โ€” pass the flags on the command line that starts the runtime server instead. (2) Duplicate hooks: the runtime de-duplicates by cache_path only when the same directory is referenced both as a marketplace install and a --plugin-dir. If two different directories contain the same plugin, both load and your hooks fire twice. Remove one, or set COPILOT_PLUGIN_DIR_ONLY=true.
Troubleshooting signalMeaning
no plugin.json or SKILL.md found in <dir>The directory exists but does not qualify as a plugin โ€” add the manifest at the root or under .github/, or a top-level SKILL.md
Plugin loads but agents/skills invisibleThe manifest must declare what it contributes, or use the implicit layout (agents/*.md, skills/*/SKILL.md). Then call session.rpc.skills.reload() to pick up changes without a restart.
Duplicate hooks firingTwo directories with the same plugin โ€” see above

MCP: connecting to external tool servers

MCP (Model Context Protocol) servers expose tools over a standard protocol, so one integration can serve every MCP-speaking agent. Configure them on the session's mcpServers map:

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();

const session = await client.createSession({
  mcpServers: {
    filesystem: {
      type: "local",
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
      tools: ["*"],
    },
  },
});

const result = await session.sendAndWait({
  prompt: "List the files in the allowed directory",
});
console.log(result?.data?.content);

await session.disconnect();
await client.stop();

Local / stdio servers

PropertyRequiredDescription
typeโ€”"local" or "stdio" (defaults to local)
commandโœ…Command to execute
argsโœ…Command arguments
envโ€”Environment variables
cwdโ€”Working directory
toolsโ€”["*"] all ยท [] none ยท explicit names to allowlist
timeoutโ€”Milliseconds

Remote servers (HTTP / SSE)

PropertyRequiredDescription
typeโœ…"http" or "sse"
urlโœ…Server URL
headersโ€”HTTP headers, e.g. for static-token auth
oauthClientIdโ€”Non-empty client ID for a statically configured OAuth client
oauthScopesโ€”Non-empty array of valid RFC 6749 scope tokens. Requires oauthClientId; used when the server challenge omits scope or sends an empty one, before protected-resource metadata fallback
oauthPublicClientโ€”Whether the client is public (no client secret)
oauthGrantTypeโ€”e.g. client_credentials
toolsโ€”Allowlist
timeoutโ€”Milliseconds

The tools field is the same allowlist pattern as availableTools, applied per server โ€” ["*"] for all, a name list to restrict, [] to disable. And you can suppress a configured server without editing the config:

const session = await client.createSession({
  mcpServers: {
    filesystem: { type: "local", command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."] },
    github: { type: "http", url: "https://api.githubcopilot.com/mcp/" },
  },
  disabledMcpServers: ["github"],
});
Disabled servers are not merely hidden. On session creation and on a cold resume, disabled servers are not started and the runtime does not initiate their authentication โ€” so disabledMcpServers is a genuine security control, not a UI filter. Caveat: a resident resume cannot undo a server the runtime has already spawned, and names are matched exactly.

MCP authentication โ€” three ownership models

Remote MCP servers that require OAuth force you to pick who owns the credential lifecycle. Choose exactly one model per authentication attempt:

1 ยท Runtime loopback mcp.oauth.login no redirectUri Runtime owns discovery, PKCE, state, exchange, persistence, refresh, reconnect least code 2 ยท Hosted callback mcp.oauth.login + HTTPS redirectUri Your host receives the callback; runtime still owns the protocol and the credentials centralised redirect 3 ยท Host-managed onMcpAuthRequest You own authorisation AND refresh. Return a token (or cancel). max control

Model 1 & 2 โ€” runtime-managed, via RPC

Wait until the server enters the needs-auth state, then call session.rpc.mcp.oauth.login. Without a redirect URI the runtime opens a local callback listener (model 1); with a trusted public HTTPS redirect URI your host receives the callback while the runtime keeps owning the protocol (model 2):

// mcp.oauth.login  (session.rpc.mcp.oauth.login)
{
  "serverName": "remote-mcp",
  "redirectUri": "https://agent.example.com/oauth/callback"
}

The selected static, CIMD, or dynamically registered OAuth client must advertise that exact URI. The URI must use HTTPS and must not contain a query or fragment. When browser interaction is required the result carries authorizationUrl and authorizationId โ€” open the URL in the user's browser and retain the ID against the target session.

// mcp.oauth.complete  (session.rpc.mcp.oauth.complete)
{
  "authorizationId": "<opaque-state>",
  "callbackUrl": "https://agent.example.com/oauth/callback?code=...&state=..."
}
Build callbackUrl from your configured public origin and path, plus the callback's original query. Do not pass an internal service URL, and do not trust client-supplied Forwarded or X-Forwarded-* headers โ€” that is a header-injection path to making the runtime accept a callback it should reject. The runtime validates origin, port, path, state, and the OAuth response before accepting delivery; token exchange, persistence, and MCP reconnect then continue asynchronously.

Model 3 โ€” host-managed, via onMcpAuthRequest

const session = await client.createSession({
  onMcpAuthRequest: async (request) => ({
    accessToken: await myIdentityProvider.getToken(request.serverUrl),
  }),
});

The callback fires whenever an MCP server responds with a 401 WWW-Authenticate challenge, and supports initial auth, refresh, reauth, and upscope flows. Return a token, or cancel the request.

Do not register a host-managed OAuth handler for an attempt that uses a runtime-managed hosted callback. Pick one model per attempt or the two owners will fight over the same credential โ€” the runtime will be mid-PKCE while your callback also tries to answer. A related historical bug is worth knowing about because it is diagnostic: an SDK once sent MCP OAuth registerInterest before session.resume, producing Session not found errors on resume with onMcpAuthRequest configured. If you see that string, suspect an SDK-version issue rather than your config.

Session-scoped MCP diagnostics: your actual debugging tool

Forget printf-debugging an MCP server. The SDK exposes bounded, in-memory, session-scoped diagnostics:

import { approveAll, CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const stop = new AbortController();
const appendLine = (line: string) => console.log(line);

await client.start();
const session = await client.createSession({
  onPermissionRequest: approveAll,
  diagnostics: { sources: { mcp: { level: "debug" } } },
});

try {
  let cursor: string | undefined;
  while (!stop.signal.aborted) {
    const page = await session.rpc.diagnostics.read({
      sources: ["mcp"],
      cursor,
      max: 100,
      waitMs: 30_000,
    });
    if (page.cursorStatus === "expired") {
      appendLine("MCP diagnostic entries were dropped.");
    }
    for (const entry of page.entries) {
      const detail = entry.details.data ? ` ${entry.details.data}` : "";
      appendLine(
        `${entry.timestamp} [${entry.level}] [${entry.source}:${entry.details.serverName}] ` +
        `${entry.message}${detail}`,
      );
    }
    cursor = page.cursor;
  }
} finally {
  await session.disconnect();
  await client.stop();
}
PropertyDetail
Opt-inEvery source defaults to off. Levels: error, warning, info, debug, trace โ€” separate from the client's process-level logLevel
Read semanticsExplicitly select sources: ["mcp"]; reading does not enable capture. One stoppable read loop per output surface, retaining its cursor.
RetentionCapped at 1,024 records / 4 MiB per session; individual records capped at 16 KiB and flagged truncated when shortened
Read boundsDefaults to 100 records, maximum 500. Reads do not consume other readers' data.
CursorsEvery successful read returns a cursor and status โ€” including empty reads. Keep it even when nothing arrives. A cursor belongs to its source selection; start without one if you change the selection. Use droppedCount on an expired cursor to show known loss.
PersistenceNeither records nor capture settings are saved in session history
Lazy startupEnabling or reading diagnostics does not start a server. Use session.rpc.mcp.startServer({ serverName }) to troubleshoot initialisation without a model request.

Re-enabling after configure({ sources: { mcp: { level: "off" } } }) can resume capture for the same live connection and its existing connectionId. Omitting diagnostics on a resident resume preserves the current configuration; a cold-loaded session needs a fresh opt-in.

Treat every diagnostic entry as sensitive. warning and above can include server stderr; debug and trace can additionally include MCP payloads, tool arguments, and paths. The runtime strips configured and structurally recognised credentials from HTTP diagnostics before entries reach the API, but that is not a guarantee about arbitrary server-provided secrets. Only selected metadata (Content-Type, Accept, MCP-Protocol-Version) is eligible for capture and its values are still untrusted. Auth headers, cookies, session IDs, query values, URL userinfo, and fragments are omitted โ€” but URL paths are retained, so never put credentials in a path segment. Do not auto-upload this to your telemetry pipeline.

The MCP debugging playbook

SymptomFirst checks
Server won't start (no tools, no errors)Use an absolute command path; chmod +x; check shared libraries with ldd; set cwd explicitly. Then reproduce it by hand โ€” run exactly the command, from exactly the expected working directory, that the SDK would run.
Server runs, no tools appearDid you set tools: ["*"] or a name list? (It must be explicit.) Does the server actually implement tools/list? Did the initialize handshake complete and did it handle notifications/initialized?
Tools listed but never calledAlmost always prompting. "What's the weather?" is vague; "Use the weather tool to get the current temperature in Seattle" names the capability. Also check defer โ€” a deferred tool may need tool search to surface.
Timeouts / JSON-RPC errorsRaise timeout; test the protocol manually by piping initialize โ†’ notifications/initialized โ†’ tools/list to the server.

MCP prompts and the pre-call hook

Two narrower surfaces complete the picture. First, prompt retrieval โ€” useful when a server publishes curated prompts you want as first-class UI:

OperationTypeScriptNotes
List promptssession.rpc.mcp.prompts.list({ serverName, cursor? })One page of typed definitions plus optional nextCursor
Get a promptsession.rpc.mcp.prompts.get({ serverName, promptName, arguments? })Argument values are strings. Omitting arguments leaves the MCP request's arguments absent; passing {} sends an explicitly empty dictionary โ€” the runtime preserves that distinction.

These target one connected server; they do not merge results across servers. Content is not flattened into text โ€” inspect each block's type before interpreting it, and note that returned messages are not automatically sent to the model; your application decides what to do with them. Refresh after an mcp.prompts.list_changed session event.

Second, the pre-MCP-tool-call hook: it lets you set, replace, or remove meta on an outbound MCP tool call. That is the seam for injecting correlation IDs, tenancy tags, or trace metadata into a server's calls without touching the server or the tool schema.

๐Ÿง  Knowledge Check

1. You attach a skills list to a custom agent, and the parent session has skills loaded. What does a sub-agent that omits skills receive?

2. Which MCP OAuth model keeps the runtime in charge of PKCE, state, token persistence, and refresh while your host merely receives the callback?

3. Why is onPreToolUse-style path checking not the right primary defence for MCP tool calls?

Further Reading