Provides an example client implementation for making API requests to the code explainer from Node.js applications
Serves as the deployment platform for the code explainer MCP, enabling serverless execution of the code analysis functionality
Offers command-line example for testing the code explanation endpoint during local development
Supports analyzing and explaining JavaScript code with comprehensive breakdown of structure and functionality
Provides client implementation examples and is listed as a prerequisite for setting up the MCP server
Supports analyzing Python code and provides example client implementation using Python's requests library
Supports analyzing TypeScript code and provides development guidelines for the server implementation
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Code Explainer MCPexplain this Python function that calculates Fibonacci numbers"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Code Explainer MCP
A Cloudflare Worker that explains source code. Given a snippet and its language, it returns a Markdown report containing an ASCII architecture diagram, a core-functionality summary, and a breakdown of the main classes and functions.
Analysis runs entirely inside the Worker using regex and pattern matching — there are no LLM calls and no external runtime dependencies. All logic lives in a single file, src/index.ts.
Features
Architecture diagram: Generates an ASCII diagram showing classes (with inheritance), standalone functions, call relationships, and imported dependencies.
Core-functionality analysis: Infers the primary and secondary purpose of the code (network, UI, data processing, database, authentication, testing, algorithm, file system) from weighted pattern matches.
Component breakdown: Lists the main classes and functions, each with a short generated description.
Multi-language support: Tailored class/function/import patterns for JavaScript, TypeScript, Python, Java, and C#, with a generic fallback for other languages.
Documentation extraction: Reuses existing JSDoc, Python docstrings, and line comments when describing a component.
Bearer-token auth: The POST endpoint is protected by a shared secret.
Related MCP server: SCAST MCP Server
How it works
explainCode(code, language) orchestrates four helpers and assembles their output into a Markdown report:
generateArchitectureDiagram— extracts classes, functions, and imports with language-specific regexes and renders an ASCII diagram, includinginherits/callsrelationships.extractCoreFunctionality— counts matches across purpose categories and produces a prose summary of the primary (and secondary) purpose.extractComponents— collects the main classes and functions;extractBlockfinds each declaration's body by brace matching (or by indentation for Python).generateComponentDescription— prefers an existing doc comment for each component and otherwise infers a description from code patterns.
A note on "MCP"
The project is named for the Model Context Protocol and keeps workers-mcp in its deploy pipeline (workers-mcp docgen runs before wrangler deploy). However, the current src/index.ts does not use workers-mcp at runtime and does not implement the MCP JSON-RPC wire protocol. It serves a plain HTTP JSON endpoint with a custom { method, params } body, handled directly by the Worker's default fetch export. Clients call it as a regular HTTP API (see Usage).
Prerequisites
Node.js 22 or higher
Wrangler (installed locally via
devDependencies)A Cloudflare account (for deployment)
Setup
Clone the repository:
git clone https://github.com/BillDuke13/code-explainer-mcp.git cd code-explainer-mcpInstall dependencies:
npm installConfigure the shared secret. For production, store it as a Worker secret (recommended):
wrangler secret put SHARED_SECRETThe
vars.SHARED_SECRETentry inwrangler.jsoncis only the placeholder"YOUR_SECRET_KEY_HERE"; never commit a real secret there. The Worker fails closed — while the secret is unset or still the placeholder, every POST returns503, so a real secret must be set before the endpoint will serve. For local development, put the secret in.dev.vars(gitignored) instead — see Local development.Deploy to Cloudflare Workers:
npm run deploy
Usage
Endpoint
Send a POST request to your Worker URL with a JSON body:
{
"method": "explainCode",
"params": ["your code here", "programming language"]
}Include the bearer token in the Authorization header:
Authorization: Bearer <SHARED_SECRET>A GET request to the same URL returns a small HTML info page instead of running an analysis.
Response
On success the response is a JSON object whose result field holds the Markdown report:
{
"result": "# Code Analysis for javascript Code\n\n## Architecture Diagram\n...\n\n## Core Functionality\n..."
}Status codes
Status | When | Body |
| Valid POST, or a |
|
| POST with a missing or incorrect |
|
|
|
|
|
|
|
| The code ( |
|
| A request method other than |
|
| Request body is not valid JSON, or another error occurs |
|
Examples
JavaScript (browser)
async function explainCode(code, language) {
const response = await fetch('https://your-worker-url.workers.dev', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer YOUR_SECRET_KEY_HERE',
},
body: JSON.stringify({
method: 'explainCode',
params: [code, language],
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.result;
}
const jsCode = `function add(a, b) { return a + b; }`;
explainCode(jsCode, 'javascript')
.then((explanation) => console.log(explanation))
.catch((error) => console.error('Error:', error));Python (requests)
import requests
def explain_code(code, language, api_url, secret_key):
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {secret_key}',
}
payload = {
'method': 'explainCode',
'params': [code, language],
}
response = requests.post(api_url, headers=headers, json=payload)
response.raise_for_status()
return response.json()['result']
code = "def hello():\n print('Hello, world!')"
explanation = explain_code(code, 'python', 'https://your-worker-url.workers.dev', 'YOUR_SECRET_KEY_HERE')
print(explanation)Node.js (axios)
const axios = require('axios');
async function explainCode(code, language) {
const response = await axios.post(
'https://your-worker-url.workers.dev',
{ method: 'explainCode', params: [code, language] },
{
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer YOUR_SECRET_KEY_HERE',
},
},
);
return response.data.result;
}Local development
Install dependencies (
npm install) if you have not already.Provide the local secret. Create a
.dev.varsfile (gitignored) sowrangler devinjects it:SHARED_SECRET=your-local-secretThe Worker fails closed, so
.dev.varsmust hold a real secret: with thewrangler.jsoncplaceholder (or no secret at all), every POST returns503.Start the dev server (http://localhost:8787):
npm run devSend a request:
curl -X POST http://localhost:8787 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-local-secret" \ -d '{"method":"explainCode","params":["function hello() { return \"Hello World\"; }","javascript"]}'
Quality checks
Tests (Vitest on
@cloudflare/vitest-pool-workers):npm test. The suite intest/drives the Worker throughSELF.fetch, covering the GET info page, auth failures, theexplainCodecontract for JavaScript and Python, empty input, and request validation.Lint (ESLint flat config):
npm run lint, ornpm run lint:fixto auto-fix.Type-check:
npx tsc --noEmitcheckssrc/. The roottsconfig.jsonexcludestest/, so type-check the tests separately withnpx tsc -p test/tsconfig.json --noEmit.Regenerate binding types: after changing bindings or vars in
wrangler.jsonc, runnpm run cf-typegento rewriteworker-configuration.d.ts.
Formatting is owned by Prettier (.prettierrc: tabs, single quotes, semicolons, printWidth 140) — run npx prettier --write ..
Project layout
src/index.ts Worker entry point and all analysis logic
test/index.spec.ts Vitest suite exercising the HTTP contract
docs/index.html Browsable HTML documentation
wrangler.jsonc Worker configurationDocumentation
Detailed, browsable documentation lives in docs/index.html — open it in a browser for the architecture overview, the analysis pipeline, the full API reference, and known limitations.
Security
The POST endpoint is protected by
Authorization: Bearer <SHARED_SECRET>.The Worker fails closed: it returns
503untilSHARED_SECRETis set to a real value (not the placeholder), so a misconfigured deploy refuses requests instead of accepting the public default.Store the secret with
wrangler secret put SHARED_SECRETfor production and in.dev.varsfor local development; never commit a real value towrangler.jsonc.The token is checked by comparing SHA-256 digests in constant time, leaking neither the secret's content nor its length through response timing. For higher-assurance deployments, add rate limiting in front of the Worker.
Request size is bounded: oversized bodies are rejected with
413(viaContent-Length), and code longer than 100,000 characters is rejected before any analysis runs.
License
This project is licensed under the Apache License 2.0 — see the LICENSE file for details.
This server cannot be installed
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/BillDuke13/code-explainer-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server
