Claude Certified Developer · Foundations

Module 3: Claude Code and MCP, safely

Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.

Practice this module

On this page

Claude Developer (Foundations) · "Ship your first Claude feature to production" · study notes

Facts checked against the Claude Code docs (code.claude.com), the MCP specification (modelcontextprotocol.io) and the MCP TypeScript SDK README on 2026-11-25. Claude Code ships often, so flags, modes and hook events change. Anything we could not confirm is marked check before relying on it.

Our angle in this module: hooks and gates on a multi-tenant SaaS platform I build, where one database holds many tenants and one careless query can leak or delete another tenant's data.


What you'll be able to do

  • Choose a Claude Code permission mode on purpose, and write permission rules that allow, ask or deny.

  • Write a short, durable CLAUDE.md that the team shares through the repo.

  • Add hooks that block dangerous tool calls (cross-tenant SQL, reading .env, pushing to main) and that run tests after edits.

  • Package a team workflow as a skill (or slash command), a subagent, or a plugin.

  • Build a small read-only MCP server whose tenant is fixed by the server, and connect it to Claude Code.

  • Apply the same trust-boundary pattern to a real company system.


Part 1: Permission modes and human gates

Claude Code can read files, edit files, run shell commands and call MCP tools. Permission modes decide how much it may do without asking you.

ModeWhat it doesWhen I use it
default (also called manual)Asks before each tool use that isn't already allowedUnfamiliar repo, anything touching config or data
acceptEditsAccepts file edits without asking; still asks for other actions such as most shell commandsRoutine coding in a repo with tests and Git
planRead-only: Claude explores and proposes a plan, but doesn't change anythingBefore a risky change; reviewing an approach
autoClaude Code approves or refuses tool calls itself, with safety checksCheck before relying on it: newer mode; read the current docs on what it auto-approves
dontAskNever prompts; tools not already allowed are refusedUnattended runs with a tight allow list (check before relying on it)
bypassPermissionsSkips permission checks entirelyOnly in a throwaway container or VM with no secrets and no network you care about

In the terminal, Shift+Tab cycles through modes (default → acceptEdits → plan, plus auto where available). To start in a mode, pass --permission-mode <mode>. bypassPermissions only joins the cycle if you start Claude Code with --allow-dangerously-skip-permissions, and the name is a fair warning.

The human gate. On a repo with real config, I approve anything that writes outside the source tree, deploys, migrates a database or pushes. Modes make routine work fast. Gates make sure the irreversible steps still pass a human.

Permission rules

Rules live in settings files under permissions, in three lists:

JSON
{
  "permissions": {
    "allow": ["Bash(npm test *)", "Bash(npm run lint *)"],
    "ask": ["Bash(git commit *)"],
    "deny": ["Read(./.env)", "Read(./.env.*)", "Bash(git push *)"]
  }
}
  • Order: deny rules are checked first, then ask, then allow, and the first match wins. A deny at any settings level beats an allow at another.

  • Syntax: Tool(specifier). For Bash the specifier is a command pattern (npm test *); for Read and Edit it is a path pattern.

  • Rules are not a sandbox. A determined shell command can reach a file by another route (cat .env instead of the Read tool, a script that reads it). Treat rules as the first layer, and add hooks (Part 3) and OS-level isolation for the things that must never happen.

Where settings live, and which wins

From highest to lowest precedence:

  1. Managed settings, deployed by your organisation (can't be overridden)

  2. Command-line arguments for this session

  3. .claude/settings.local.json: personal, for this project, not committed (Claude Code adds it to your global gitignore when it creates it)

  4. .claude/settings.json: shared with the team, committed to the repo

  5. ~/.claude/settings.json: your personal defaults for every project

Team rules and hooks go in .claude/settings.json, so everyone who clones the repo gets the same gates.


Part 2: Durable project context, CLAUDE.md

CLAUDE.md is a Markdown file Claude Code loads into context at the start of a session. It holds what a new teammate needs on day one.

Where it can live:

FileScope
./CLAUDE.md or ./.claude/CLAUDE.mdThe project; committed and shared
./CLAUDE.local.mdYou, in this project; keep it out of Git
~/.claude/CLAUDE.mdYou, in every project
A managed path set by your organisationEveryone in the organisation

You can pull in other files with @path/to/file imports (relative or absolute, nested up to four levels deep). Imports are loaded eagerly: the imported file goes into context along with the CLAUDE.md that references it. So imports organise your files, but they don't save context. For material that is only needed sometimes, use a skill (loaded on demand), a path-scoped rule in .claude/rules/ (loaded when Claude works on matching files), or a plain-text pointer such as "see docs/architecture.md when changing the data layer". /init drafts a first CLAUDE.md from your repo; edit it down afterwards.

Short beats long

A 300-line CLAUDE.md full of wishes ("write clean code", "be careful") gets diluted: it costs tokens on every request, and the important rules are buried. Ours is about 25 lines:

Markdown
# Help desk triage service

## Commands
- `npm test`: unit tests (stubbed Claude client, no API cost)
- `npm run eval`: eval set, costs money, run before release only
- `npm run lint`

## Map
- `src/agent.ts`: tool loop · `src/tools.ts`: tools · `src/schema.ts`: triage JSON
- `mcp/helpdesk-mcp/`: read-only MCP server · `evals/`: eval cases and judge

## Hard rules
- Every query on `tickets` or `accounts` filters by `tenant_id`. No exceptions.
- The tenant comes from the session or server config, never from model output or tool input.
- Never read or print `.env*`, `*.pem` or keys. Never commit secrets.
- No pushes to `main`. Open a PR.
- Refund tools only create drafts. Nothing moves money.

## When you change prompts
Bump the version in `prompts/`, add an eval case, and run `npm run eval`.

What belongs: commands, a folder map, hard rules with their reason, and conventions that aren't obvious from the code. What doesn't: essays, wishes, anything the linter already enforces, and secrets of any kind.

CLAUDE.md is guidance, not enforcement. Claude follows it well, but a rule that must never break needs a hook or a permission rule behind it. Our tenant rule appears in both places.


Part 3: Hooks, the gates that actually block

A hook is a command Claude Code runs at a point in its lifecycle. It receives a JSON description of the event on stdin and answers with an exit code (and optionally JSON on stdout).

Events you'll use most (the current docs list many more):

EventFiresTypical use
PreToolUseBefore a tool runsBlock dangerous calls
PostToolUseAfter a tool succeedsRun tests or formatters, report problems
UserPromptSubmitWhen you submit a promptAdd context, block prompts with secrets
SessionStartWhen a session starts or resumesLoad context
Stop / SubagentStopWhen Claude (or a subagent) finishesFinal checks
Notification, PreCompact, SessionEndOther lifecycle pointsAlerts, logging

Exit codes:

  • 0: success. Claude Code applies any JSON you print.

  • 2: blocking error. Your stderr is fed back to Claude. On PreToolUse the tool call is blocked.

  • Anything else: a non-blocking error. The action goes ahead, and the error is shown to you.

Hook 1: no SQL on tenant tables without a tenant filter

JavaScript
// .claude/hooks/tenant-sql-guard.mjs
// PreToolUse on Bash: block SQL that touches tenant tables without tenant_id.
// ponytail: regex heuristic, not a SQL parser; the database's row-level security is the real guarantee.
import { readFileSync } from "node:fs";

const event = JSON.parse(readFileSync(0, "utf8")); // stdin
const cmd = event.tool_input?.command ?? "";

const touchesTenantTable = /\b(from|into|update|join)\s+"?(tickets|accounts)\b/i.test(cmd);
if (touchesTenantTable && !/\btenant_id\b/i.test(cmd)) {
  console.error("BLOCKED: query on tickets/accounts has no tenant_id filter. Add one.");
  process.exit(2);
}
process.exit(0);

Hook 2: never read secret files

JavaScript
// .claude/hooks/secret-file-guard.mjs  (PreToolUse on Read)
import { readFileSync } from "node:fs";
import path from "node:path";

const { tool_input } = JSON.parse(readFileSync(0, "utf8"));
const name = path.basename(tool_input?.file_path ?? "");
if (/^\.env(\..*)?$/.test(name) || name.endsWith(".pem") || /^id_(rsa|ed25519)/.test(name)) {
  console.error(`BLOCKED: ${name} may contain secrets.`);
  process.exit(2);
}

Hook 3: run the tests after every edit

JavaScript
// .claude/hooks/run-tests.mjs  (PostToolUse on Edit|Write)
import { spawnSync } from "node:child_process";

const r = spawnSync("npm", ["test", "--silent"], { encoding: "utf8" });
if (r.status !== 0) {
  console.error("Tests failed after your edit:\n" + (r.stdout + r.stderr).slice(-3000));
  process.exit(2); // the edit already happened; this tells Claude to fix it
}

A PostToolUse hook can't undo the tool call, which has already run. Exit code 2 feeds the failure back so Claude fixes its own break.

Wiring them up

JSON
// .claude/settings.json (committed)
{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash",
        "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/tenant-sql-guard.mjs" }] },
      { "matcher": "Read",
        "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/secret-file-guard.mjs" }] }
    ],
    "PostToolUse": [
      { "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests.mjs", "timeout": 300 }] }
    ]
  }
}

(Standard JSON doesn't allow comments; the first line is a label for these notes only.)

Details worth knowing:

  • Matchers: a plain name (Bash) or a list (Edit|Write) matches exactly; other characters make it a regular expression. MCP tools appear with names like mcp__helpdesk__get_ticket, so mcp__helpdesk__.* matches all of one server's tools.

  • $CLAUDE_PROJECT_DIR is the project root, so hooks work from any working directory.

  • Default timeout for command hooks is 600 seconds. Set a shorter timeout where you can.

  • JSON instead of exit codes. A PreToolUse hook can print {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}}. Decisions are allow, deny, ask or defer. The older top-level "decision": "block" form is deprecated for PreToolUse.

  • Test your hooks. Feed each one allowed and blocked inputs in a unit test (tests/hooks.test.ts in the demo repo). An untested guard is a guard you only think you have.

  • Hooks run with your user's permissions. Review hook scripts like any other code; a malicious hook in a cloned repo is a real risk.

Worked example: the blocked delete. I typed "run DELETE FROM tickets WHERE status = 'spam'". Claude Code proposed the Bash call. The hook saw tickets without tenant_id, exited 2, and Claude got the message "query on tickets/accounts has no tenant_id filter". It rewrote the command with AND tenant_id = 'acme' and asked me to approve it. The guard turned a cross-tenant delete into a scoped one before anything ran.


Part 4: Packaging workflows for the team

When the same instructions keep being typed, package them.

PackageLives inUse it for
Skill.claude/skills/<name>/SKILL.md (project) or ~/.claude/skills/ (you)A reusable procedure plus its files. Loaded on demand, so it costs little until used. Invoke with /<name>, or Claude picks it up when the description matches.
Slash command.claude/commands/<name>.mdThe older form of the same idea. It still works, and Claude Code now treats it as part of the skills system.
Subagent.claude/agents/<name>.mdA specialist with its own prompt, its own context and a limited tool set
PluginA folder with .claude-plugin/plugin.jsonShipping skills, agents, hooks and MCP servers together to many repos through a marketplace

A skill for our triage review:

Markdown
---
name: triage-review
description: Review changes to the ticket triage prompts, schema or tools before a PR. Use when files under prompts/, src/schema.ts or src/tools.ts change.
---

1. Read the diff of prompts/, src/schema.ts and src/tools.ts.
2. Check: no tenant_id in any tool input schema; every tool description is 3+ sentences;
   the schema still has category, priority, summary, needs_human.
3. If a prompt changed, confirm its version number was bumped and an eval case was added.
4. Run `npm test`. Do not run `npm run eval` without asking.
5. Report findings as a short list: blocking, should fix, fine.

Frontmatter fields are optional, but write the description: it is how Claude knows when the skill applies. The name defaults to the folder name.

A subagent that may only read:

Markdown
---
name: tenant-auditor
description: Audits code for queries or tools that could cross tenant boundaries. Use before merging data-access changes.
tools: Read, Grep, Glob
---
You look for data access that is not scoped by tenant_id ...

Because tools lists only read tools, this subagent can't edit or run anything. (Leave tools out and it inherits everything, which is rarely what you want for an auditor.)


Part 5: MCP servers

The Model Context Protocol (MCP) is an open protocol for connecting AI applications to tools and data. An MCP server exposes capabilities; an MCP client (Claude Code, Claude Desktop, your own app) connects to it.

What a server can offer:

  • Tools: actions the model can call (list_open_tickets, get_ticket)

  • Resources: data the application or user can attach as context (a ticket, a file)

  • Prompts: reusable prompt templates a user can pick

Clients can offer features back to servers too, such as elicitation (the server asking the user for input). Check before relying on it: the current spec revision (2026-07-28) lists client features differently from older material you may find online.

Transports (how client and server talk): stdio (the client starts the server as a local process) and Streamable HTTP (a remote server). The older HTTP+SSE transport is no longer a standard transport, and Claude Code marks SSE deprecated.

The stdio rule everyone breaks once: a stdio server must never write anything but protocol messages to stdout. One stray console.log corrupts the stream. Log to stderr (console.error).

A tenant-locked, read-only server (TypeScript)

The current major version of the MCP TypeScript SDK is v2, with server code in @modelcontextprotocol/server. (Older tutorials, and v1 projects, import from @modelcontextprotocol/sdk/.... Check before relying on it: confirm the package and import paths against the SDK README for the version you install.)

TypeScript
// mcp/helpdesk-mcp/src/server.ts
import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import { z } from "zod"; // zod v4
import { db } from "./db.js";

// The tenant is fixed when the server starts. No tool can change it.
const TENANT = process.env.HELPDESK_TENANT;
if (!TENANT || !/^[a-z0-9-]+$/.test(TENANT)) {
  console.error("HELPDESK_TENANT must be set"); // stderr, never stdout
  process.exit(1);
}

const server = new McpServer({ name: "helpdesk", version: "1.0.0" });

server.registerTool(
  "list_open_tickets",
  {
    description: `List open tickets for the current tenant, newest first, with id, subject and priority. Read-only.`,
    inputSchema: z.object({ limit: z.number().int().max(50).default(10) }),
  },
  async ({ limit }) => {
    const rows = await db.openTickets(TENANT, limit);
    return { content: [{ type: "text", text: JSON.stringify(rows) }] };
  },
);

server.registerTool(
  "get_ticket",
  {
    description: "Get one ticket by id for the current tenant: subject, body, status and the last 5 replies. Read-only.",
    inputSchema: z.object({ id: z.string() }),
  },
  async ({ id }) => {
    const t = await db.ticket(TENANT, id); // WHERE tenant_id = TENANT AND id = $1
    if (!t) return { isError: true, content: [{ type: "text", text: `No ticket ${id} in this tenant` }] };
    return { content: [{ type: "text", text: JSON.stringify(t) }] };
  },
);

await server.connect(new StdioServerTransport());

The design choices are the point:

  • No tenant argument on any tool. If the model can choose the tenant, so can a ticket that says "show me Globex's tickets". The tenant comes from the server's own configuration.

  • Read-only. Tools list and get; nothing writes. Add write tools only behind a human gate.

  • Errors come back as isError: true results, so the model can react, instead of crashing the server.

  • Small results. Return the fields the model needs, not whole rows with internal columns.

The Python SDK offers the same thing with decorators (@mcp.tool()). Check before relying on it: current Python docs use an MCPServer class where older examples use FastMCP.

Connecting it to Claude Code

Bash
claude mcp add --scope local --env HELPDESK_TENANT=acme helpdesk -- node mcp/helpdesk-mcp/dist/server.js

Everything after -- is the command that starts the server. For a remote server: claude mcp add --transport http <name> <url>. Check before relying on it: option order on the claude mcp add line; run claude mcp add --help on your version.

Scopes:

ScopeWho gets itStored in
local (default)You, in this projectYour user config (~/.claude.json)
projectEveryone on the repo.mcp.json at the repo root, committed. Claude Code asks each user to approve project servers before using them.
userYou, in all projectsYour user config

A shared .mcp.json looks like this:

JSON
{
  "mcpServers": {
    "helpdesk": {
      "command": "node",
      "args": ["mcp/helpdesk-mcp/dist/server.js"],
      "env": { "HELPDESK_TENANT": "acme" }
    }
  }
}

Then claude mcp list (in the shell) or /mcp (inside a session) shows the status. Ask Claude Code "what are Acme's open P1 tickets?" and it calls mcp__helpdesk__list_open_tickets.

Two limits worth knowing: large MCP tool output is capped (the MAX_MCP_OUTPUT_TOKENS setting, default 25,000 tokens), so design tools to return summaries and IDs; and every MCP server you add is code you trust with your context and possibly your credentials, so review third-party servers as carefully as dependencies.


Part 6: Enterprise integration

Swap the fake help desk for a real company system (a CRM, a ticketing system, an identity provider) and the pattern stays the same. The MCP server is the trust boundary.

  • Identity: the server uses a credential scoped to one tenant, read-only, and short-lived (minutes or hours, not a long-lived admin key). If the server is compromised or misused, the damage stays small. This is the same least-privilege thinking we use for OAuth clients in identity work: the agent gets the narrowest token that does the job.

  • Remote servers: Streamable HTTP servers can protect themselves with OAuth-based authorisation in the MCP spec. Check before relying on it: the spec's authorisation section for the revision you target.

  • Logging: log every tool call with tenant, tool, arguments (redacted where needed), caller and result size. You'll need it for audits and incident review.

  • Rate limits and timeouts on the server side, so a looping agent can't hammer the company system.

  • Untrusted output: data returned by a tool (an email body, a ticket) is untrusted input to the model. It may contain instructions. Module 4 tests this.

Claude Code without a human at the keyboard

For CI and scripts, claude -p "<prompt>" runs one task non-interactively. --output-format json (or stream-json) gives machine-readable output, --allowedTools limits what it may use, and --max-turns caps the loop. In unattended runs, a tight allow list plus hooks is what stands between a bad prompt and your repo. Check before relying on it: newer flags such as --bare are recommended for scripted calls in current docs.

Undo

Claude Code checkpoints file edits made through its own edit tools. /rewind (or Esc twice on an empty prompt) restores them. It does not undo side effects of shell commands: a migration that ran, a file deleted with rm, or a push. That's another reason the irreversible actions need gates.


Common mistakes and how to spot them

MistakeHow to spot itFix
bypassPermissions on a laptop with real credentialsClaude ran something you never sawUse acceptEdits or plan; bypass only in a disposable sandbox
Relying on CLAUDE.md alone for a hard ruleThe rule is broken "once in a while"Back hard rules with a hook or deny rule
A 300-line CLAUDE.mdImportant rules ignored; high token use per requestCommands, map, hard rules; ~25–50 lines; move occasional material into skills or path-scoped rules (imports load eagerly)
Hooks committed but never testedA guard that silently allows everythingUnit-test each hook with allowed and blocked inputs
PostToolUse hook expected to prevent an actionThe edit happened anywayUse PreToolUse to block; PostToolUse to report and fix
Hook exits 1 to "block"The action still runsExit 2 (or return a deny decision)
Team rules in settings.local.jsonTeammates don't get the gatesShared rules in .claude/settings.json
tenant as an MCP tool argumentA ticket or prompt can request another tenant's dataFix the tenant in server config
console.log in a stdio MCP serverClient shows parse errors; server "disconnects"Log to stderr
One long-lived admin key in an MCP serverOne leak exposes everythingScoped, read-only, short-lived credentials per tenant
Expecting /rewind to undo a migrationData changed but code restoredGate irreversible commands; back up before migrations
Following old MCP tutorials blindlyImport errors, removed methods such as server.tool()Match the SDK major version you install

Remember

  1. Pick the permission mode on purpose; bypassPermissions only in a throwaway sandbox.

  2. Permission rules: deny is checked first, and a deny anywhere beats an allow.

  3. Team gates live in .claude/settings.json; personal ones in settings.local.json.

  4. Keep CLAUDE.md short: commands, map, hard rules; it guides but doesn't enforce.

  5. Hooks read JSON on stdin; exit 2 blocks a PreToolUse call and sends stderr to Claude.

  6. PostToolUse can't undo; use it to run tests and feed failures back.

  7. Package repeat work as skills; give subagents only the tools they need.

  8. MCP servers offer tools, resources and prompts over stdio or Streamable HTTP.

  9. Never put the tenant in an MCP tool argument; fix it in the server's config.

  10. stdio servers write protocol only to stdout; logs go to stderr.


Practice: mcq/module-03.md · Previous: Module 2 · Next: Module 4: Prove it works in production · Course home: README.md

↑ ↓ navigate · ↵ select · esc close