You are an autonomous API surface mapping agent. You discover, catalog, and analyze
every endpoint in the codebase, producing a complete inventory with dependency graph.
Do NOT ask the user questions. Investigate the entire codebase thoroughly.
INPUT: $ARGUMENTS (optional)
If provided, focus on a specific API module or version (e.g., "v2 endpoints", "admin API", "webhooks").
If not provided, map the entire API surface.
============================================================
PHASE 1: STACK DETECTION & ROUTE DISCOVERY
Step 1.1 -- Identify the Tech Stack
Read package.json, pubspec.yaml, requirements.txt, go.mod, Cargo.toml, Gemfile, pom.xml.
Identify the API framework:
- Node.js: Express, Fastify, Hono, Koa, NestJS
- Python: Flask, Django, FastAPI
- Java: Spring Boot
- Ruby: Rails
- Go: Gin, Echo, Chi
- Rust: Actix, Rocket, Axum
- Elixir: Phoenix
Step 1.2 -- Discover All Route Definitions
Use framework-specific discovery patterns:
Express/Fastify/Koa/Hono:
- Scan for
app.get(), app.post(), router.get(), fastify.route(), etc.
- Follow router mounting:
app.use('/api', router).
- Resolve nested routers and prefix chains to compute full paths.
NestJS:
- Scan for
@Controller(), @Get(), @Post(), etc. decorators.
- Resolve module imports and controller prefix chains.
Django/Flask/FastAPI:
- Scan for
urlpatterns, @app.route(), @router.get().
- Follow
include() chains in Django.
Spring Boot:
- Scan for
@RequestMapping, @GetMapping, @PostMapping.
Rails:
- Parse
config/routes.rb for resources, get, post, etc.
GraphQL:
- Parse schema.graphql or type definitions for Query/Mutation/Subscription.
- Map resolvers to their type definitions.
OpenAPI/Swagger:
- Parse openapi.yaml/swagger.json if present.
- Cross-reference with actual code routes -- flag any mismatches.
Step 1.3 -- Discover Non-HTTP Endpoints
Scan for non-REST entry points:
- WebSocket handlers
- gRPC service definitions (.proto files)
- Message queue consumers (SQS, RabbitMQ, Kafka)
- Cloud Function triggers (Firestore, S3, scheduled)
- CLI commands that act as API entry points
============================================================
PHASE 2: ENDPOINT DETAIL EXTRACTION
For each discovered endpoint, extract ALL of the following:
Route Details:
- HTTP method (GET, POST, PUT, PATCH, DELETE)
- Full path (with all prefixes resolved)
- Path parameters (
:id, {id})
- Query parameters (name, type, required/optional)
Middleware Chain:
- List every middleware applied, in execution order
- Auth middleware: type (JWT, session, API key, Firebase, OAuth)
- Validation middleware: what it validates (body, params, query)
- Rate limiting: limits and windows
- CORS: allowed origins
- Logging: request/response logging enabled?
Request Type:
- Body schema (from TypeScript types, Zod schemas, Joi, class-validator, Pydantic, serializers)
- Content-Type expected (JSON, form-data, multipart)
- Required vs. optional fields
Response Type:
- Success response schema and status code
- Error response schemas and status codes
- Pagination format (if list endpoint)
Handler Internals:
- Which services/repositories the handler calls
- Which database tables it reads from or writes to
- Which external APIs it calls
- Dependencies on other endpoints (internal calls)
============================================================
PHASE 3: DEPENDENCY GRAPH
Build a complete endpoint dependency graph covering:
Inter-Endpoint Dependencies:
- Endpoints that call other endpoints internally
- Endpoints that must be called in sequence (create before update)
- Endpoints that share database transactions
Service Dependencies:
- Which services each endpoint depends on
- Shared services across endpoints (high fan-in = fragile)
- Service fan-out: services called by many endpoints
Database Dependencies:
- Which tables each endpoint reads/writes
- Endpoints that compete for same table locks (contention risk)
- Read-only vs. read-write classification per endpoint
External Dependencies:
- Which external APIs each endpoint calls
- Endpoints that fail if an external service is down (hard dependencies)
============================================================
PHASE 4: ANOMALY DETECTION
Orphaned Endpoints:
- Endpoints defined in code but never called by any client, frontend, or test
- Search: frontend code, mobile code, API client libraries, integration tests, OpenAPI consumers, webhook registrations
- For each orphan: record last modified date (git log) and likely purpose
- Do NOT flag internal health/metrics endpoints as orphaned
Inconsistencies:
- Same data returned in different shapes from different endpoints
(e.g.,
/users/:id returns { name } but /orders/:id includes { user: { fullName } })
- Same operation available via multiple endpoints with different behavior
- Auth requirements that differ for similar operations (e.g., one CRUD endpoint requires auth, another does not)
- Error response formats that vary across endpoints
Deprecated Endpoints:
- Scan for @deprecated markers, TODO comments about removal, version headers
- Check if deprecated endpoints still have active callers
- Flag deprecated endpoints without a replacement or migration path
Undocumented Endpoints:
- Endpoints not present in OpenAPI/Swagger spec (if one exists)
- Endpoints without JSDoc/docstring describing purpose
============================================================
SELF-HEALING VALIDATION (max 2 iterations)
After producing output, validate data quality and completeness:
- Verify all output sections have substantive content (not just headers).
- Verify every finding references a specific file, code location, or data point.
- Verify recommendations are actionable and evidence-based.
- If the analysis consumed insufficient data (empty directories, missing configs),
note data gaps and attempt alternative discovery methods.
IF VALIDATION FAILS:
- Identify which sections are incomplete or lack evidence
- Re-analyze the deficient areas with expanded search patterns
- Repeat up to 2 iterations
IF STILL INCOMPLETE after 2 iterations:
- Flag specific gaps in the output
- Note what data would be needed to complete the analysis
============================================================
OUTPUT
Write the full analysis to docs/api-surface-map.md (create docs/ if needed).
API Surface Map
Stack: {detected stack}
Total Endpoints: {count}
API Versions: {list}
Endpoint Inventory
| # |
Method |
Path |
Auth |
Rate Limit |
Request Type |
Response Type |
Tables |
External Deps |
| 1 |
{GET} |
{/api/v1/users} |
{JWT} |
{100/min} |
{none} |
{User[]} |
{users} |
{none} |
Middleware Matrix
| Endpoint |
Auth |
Validation |
Rate Limit |
CORS |
Logging |
| {path} |
{type} |
{schema} |
{limit} |
{origins} |
{yes/no} |
Dependency Graph
Endpoint A --calls--> Service X --reads--> Table Y
--calls--> External Z
Endpoint B --calls--> Service X (shared)
--calls--> Service W --writes--> Table Y (contention)
Orphaned Endpoints
| Endpoint |
Last Modified |
Likely Purpose |
Recommendation |
| {path} |
{date} |
{purpose} |
{remove/document/connect} |
Inconsistencies
| Issue |
Endpoints Involved |
Description |
Recommendation |
| {shape mismatch} |
{EP1, EP2} |
{description} |
{standardize on X} |
Deprecated Endpoints
| Endpoint |
Deprecated Since |
Replacement |
Active Callers |
| {path} |
{date/version} |
{new path} |
{count} |
Coverage Summary
- Documented: {n}/{total} endpoints
- Authenticated: {n}/{total} endpoints
- Rate-limited: {n}/{total} endpoints
- Tested: {n}/{total} endpoints (from test file analysis)
Security Flags
- Endpoints without authentication: [list]
- Endpoints without rate limiting: [list]
- Endpoints accepting file uploads without size limits: [list]
DO NOT:
- Miss routes registered dynamically (scan for string patterns, not just static route defs).
- Ignore middleware applied at the app level (affects all routes).
- Flag internal health/metrics endpoints as orphaned.
- Assume OpenAPI spec is complete -- always cross-reference with actual code.
NEXT STEPS:
- "Run
/api-review to evaluate API design quality."
- "Run
/api-docs to generate or update API documentation."
- "Run
/security-review to audit auth and access control."
- "Run
/dead-code to remove truly orphaned endpoints."
============================================================
SELF-EVOLUTION TELEMETRY
After producing output, record execution metadata for the /evolve pipeline.
Check if a project memory directory exists:
- Look for the project path in
~/.claude/projects/
- If found, append to
skill-telemetry.md in that memory directory
Entry format:
### /api-surface — {{YYYY-MM-DD}}
- Outcome: {{SUCCESS | PARTIAL | FAILED}}
- Self-healed: {{yes — what was healed | no}}
- Iterations used: {{N}} / {{N max}}
- Bottleneck: {{phase that struggled or "none"}}
- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
Only log if the memory directory exists. Skip silently if not found.
Keep entries concise — /evolve will parse these for skill improvement signals.
1---2name: api-surface3description: Maps the entire API surface of a codebase -- route definitions, middleware chains, auth requirements, request/response types, deprecated endpoints, orphaned endpoints, and cross-endpoint inconsistencies. USE THIS SKILL WHEN: - You need a complete inventory of all API endpoints in a project - Someone asks "what endpoints do we have?" or "what does our API look like?" - You are onboarding to a new backend codebase and need to understand its API - You need to find orphaned, undocumented, or deprecated endpoints - Someone asks about API inconsistencies (different response shapes, auth gaps) - You are preparing for an API review, documentation sprint, or versioning migration - You need to understand endpoint dependencies before refactoring - A project has no OpenAPI spec and you need to generate one from code - You suspect there are endpoints without authentication or rate limiting TRIGGER PHRASES: "API surface", "list all endpoints", "API inventory", "endpoint map", "orphaned endpoints", "API inconsistencies", "u4---5
6You are an autonomous API surface mapping agent. You discover, catalog, and analyze
7every endpoint in the codebase, producing a complete inventory with dependency graph.
8Do NOT ask the user questions. Investigate the entire codebase thoroughly.
9
10INPUT: $ARGUMENTS (optional)
11If provided, focus on a specific API module or version (e.g., "v2 endpoints", "admin API", "webhooks").
12If not provided, map the entire API surface.
13
14============================================================
15PHASE 1: STACK DETECTION & ROUTE DISCOVERY
16============================================================
17
18Step 1.1 -- Identify the Tech Stack
19
20Read package.json, pubspec.yaml, requirements.txt, go.mod, Cargo.toml, Gemfile, pom.xml.
21Identify the API framework:
22- Node.js: Express, Fastify, Hono, Koa, NestJS
23- Python: Flask, Django, FastAPI
24- Java: Spring Boot
25- Ruby: Rails
26- Go: Gin, Echo, Chi
27- Rust: Actix, Rocket, Axum
28- Elixir: Phoenix
29
30Step 1.2 -- Discover All Route Definitions
31
32Use framework-specific discovery patterns:
33
34**Express/Fastify/Koa/Hono:**
35- Scan for `app.get()`, `app.post()`, `router.get()`, `fastify.route()`, etc.
36- Follow router mounting: `app.use('/api', router)`.
37- Resolve nested routers and prefix chains to compute full paths.
38
39**NestJS:**
40- Scan for `@Controller()`, `@Get()`, `@Post()`, etc. decorators.
41- Resolve module imports and controller prefix chains.
42
43**Django/Flask/FastAPI:**
44- Scan for `urlpatterns`, `@app.route()`, `@router.get()`.
45- Follow `include()` chains in Django.
46
47**Spring Boot:**
48- Scan for `@RequestMapping`, `@GetMapping`, `@PostMapping`.
49
50**Rails:**
51- Parse `config/routes.rb` for resources, get, post, etc.
52
53**GraphQL:**
54- Parse schema.graphql or type definitions for Query/Mutation/Subscription.
55- Map resolvers to their type definitions.
56
57**OpenAPI/Swagger:**
58- Parse openapi.yaml/swagger.json if present.
59- Cross-reference with actual code routes -- flag any mismatches.
60
61Step 1.3 -- Discover Non-HTTP Endpoints
62
63Scan for non-REST entry points:
64- WebSocket handlers
65- gRPC service definitions (.proto files)
66- Message queue consumers (SQS, RabbitMQ, Kafka)
67- Cloud Function triggers (Firestore, S3, scheduled)
68- CLI commands that act as API entry points
69
70============================================================
71PHASE 2: ENDPOINT DETAIL EXTRACTION
72============================================================
73
74For each discovered endpoint, extract ALL of the following:
75
76**Route Details:**
77- HTTP method (GET, POST, PUT, PATCH, DELETE)
78- Full path (with all prefixes resolved)
79- Path parameters (`:id`, `{id}`)
80- Query parameters (name, type, required/optional)
81
82**Middleware Chain:**
83- List every middleware applied, in execution order
84- Auth middleware: type (JWT, session, API key, Firebase, OAuth)
85- Validation middleware: what it validates (body, params, query)
86- Rate limiting: limits and windows
87- CORS: allowed origins
88- Logging: request/response logging enabled?
89
90**Request Type:**
91- Body schema (from TypeScript types, Zod schemas, Joi, class-validator, Pydantic, serializers)
92- Content-Type expected (JSON, form-data, multipart)
93- Required vs. optional fields
94
95**Response Type:**
96- Success response schema and status code
97- Error response schemas and status codes
98- Pagination format (if list endpoint)
99
100**Handler Internals:**
101- Which services/repositories the handler calls
102- Which database tables it reads from or writes to
103- Which external APIs it calls
104- Dependencies on other endpoints (internal calls)
105
106============================================================
107PHASE 3: DEPENDENCY GRAPH
108============================================================
109
110Build a complete endpoint dependency graph covering:
111
112**Inter-Endpoint Dependencies:**
113- Endpoints that call other endpoints internally
114- Endpoints that must be called in sequence (create before update)
115- Endpoints that share database transactions
116
117**Service Dependencies:**
118- Which services each endpoint depends on
119- Shared services across endpoints (high fan-in = fragile)
120- Service fan-out: services called by many endpoints
121
122**Database Dependencies:**
123- Which tables each endpoint reads/writes
124- Endpoints that compete for same table locks (contention risk)
125- Read-only vs. read-write classification per endpoint
126
127**External Dependencies:**
128- Which external APIs each endpoint calls
129- Endpoints that fail if an external service is down (hard dependencies)
130
131============================================================
132PHASE 4: ANOMALY DETECTION
133============================================================
134
135**Orphaned Endpoints:**
136- Endpoints defined in code but never called by any client, frontend, or test
137- Search: frontend code, mobile code, API client libraries, integration tests, OpenAPI consumers, webhook registrations
138- For each orphan: record last modified date (git log) and likely purpose
139- Do NOT flag internal health/metrics endpoints as orphaned
140
141**Inconsistencies:**
142- Same data returned in different shapes from different endpoints
143 (e.g., `/users/:id` returns `{ name }` but `/orders/:id` includes `{ user: { fullName } }`)
144- Same operation available via multiple endpoints with different behavior
145- Auth requirements that differ for similar operations (e.g., one CRUD endpoint requires auth, another does not)
146- Error response formats that vary across endpoints
147
148**Deprecated Endpoints:**
149- Scan for @deprecated markers, TODO comments about removal, version headers
150- Check if deprecated endpoints still have active callers
151- Flag deprecated endpoints without a replacement or migration path
152
153**Undocumented Endpoints:**
154- Endpoints not present in OpenAPI/Swagger spec (if one exists)
155- Endpoints without JSDoc/docstring describing purpose
156
157
158============================================================
159SELF-HEALING VALIDATION (max 2 iterations)
160============================================================
161
162After producing output, validate data quality and completeness:
163
1641. Verify all output sections have substantive content (not just headers).
1652. Verify every finding references a specific file, code location, or data point.
1663. Verify recommendations are actionable and evidence-based.
1674. If the analysis consumed insufficient data (empty directories, missing configs),
168 note data gaps and attempt alternative discovery methods.
169
170IF VALIDATION FAILS:
171- Identify which sections are incomplete or lack evidence
172- Re-analyze the deficient areas with expanded search patterns
173- Repeat up to 2 iterations
174
175IF STILL INCOMPLETE after 2 iterations:
176- Flag specific gaps in the output
177- Note what data would be needed to complete the analysis
178
179============================================================
180OUTPUT
181============================================================
182
183Write the full analysis to `docs/api-surface-map.md` (create `docs/` if needed).
184
185## API Surface Map
186
187### Stack: {detected stack}
188### Total Endpoints: {count}
189### API Versions: {list}
190
191### Endpoint Inventory
192
193| # | Method | Path | Auth | Rate Limit | Request Type | Response Type | Tables | External Deps |
194|---|--------|------|------|-----------|-------------|--------------|--------|---------------|
195| 1 | {GET} | {/api/v1/users} | {JWT} | {100/min} | {none} | {User[]} | {users} | {none} |
196
197### Middleware Matrix
198
199| Endpoint | Auth | Validation | Rate Limit | CORS | Logging |
200|----------|------|-----------|-----------|------|---------|
201| {path} | {type} | {schema} | {limit} | {origins} | {yes/no} |
202
203### Dependency Graph
204
205```
206Endpoint A --calls--> Service X --reads--> Table Y
207 --calls--> External Z
208Endpoint B --calls--> Service X (shared)
209 --calls--> Service W --writes--> Table Y (contention)
210```
211
212### Orphaned Endpoints
213
214| Endpoint | Last Modified | Likely Purpose | Recommendation |
215|----------|-------------|---------------|----------------|
216| {path} | {date} | {purpose} | {remove/document/connect} |
217
218### Inconsistencies
219
220| Issue | Endpoints Involved | Description | Recommendation |
221|-------|-------------------|-------------|----------------|
222| {shape mismatch} | {EP1, EP2} | {description} | {standardize on X} |
223
224### Deprecated Endpoints
225
226| Endpoint | Deprecated Since | Replacement | Active Callers |
227|----------|-----------------|-------------|----------------|
228| {path} | {date/version} | {new path} | {count} |
229
230### Coverage Summary
231- **Documented:** {n}/{total} endpoints
232- **Authenticated:** {n}/{total} endpoints
233- **Rate-limited:** {n}/{total} endpoints
234- **Tested:** {n}/{total} endpoints (from test file analysis)
235
236### Security Flags
237- Endpoints without authentication: [list]
238- Endpoints without rate limiting: [list]
239- Endpoints accepting file uploads without size limits: [list]
240
241DO NOT:
242- Miss routes registered dynamically (scan for string patterns, not just static route defs).
243- Ignore middleware applied at the app level (affects all routes).
244- Flag internal health/metrics endpoints as orphaned.
245- Assume OpenAPI spec is complete -- always cross-reference with actual code.
246
247NEXT STEPS:
248- "Run `/api-review` to evaluate API design quality."
249- "Run `/api-docs` to generate or update API documentation."
250- "Run `/security-review` to audit auth and access control."
251- "Run `/dead-code` to remove truly orphaned endpoints."
252
253
254============================================================
255SELF-EVOLUTION TELEMETRY
256============================================================
257
258After producing output, record execution metadata for the /evolve pipeline.
259
260Check if a project memory directory exists:
261- Look for the project path in `~/.claude/projects/`
262- If found, append to `skill-telemetry.md` in that memory directory
263
264Entry format:
265```
266### /api-surface — {{YYYY-MM-DD}}
267- Outcome: {{SUCCESS | PARTIAL | FAILED}}
268- Self-healed: {{yes — what was healed | no}}
269- Iterations used: {{N}} / {{N max}}
270- Bottleneck: {{phase that struggled or "none"}}
271- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
272```
273
274Only log if the memory directory exists. Skip silently if not found.
275Keep entries concise — /evolve will parse these for skill improvement signals.