chore: remove dead code and fix HTTP port-conflict startup (#351)

* chore: remove dead code and fix HTTP port-conflict startup

- drop unused helpers, constants, schemas, and duplicated types
- exit non-zero when the HTTP port is already in use
- add stdio and port-conflict tests
- clean dist on build, add serve:http, fix inspector:http for Inspector v2

* test: harden port-conflict test; drop unreachable listen guard

- pin the child's host so BRAVE_MCP_HOST cannot bypass the conflict
- bound the exit wait and reject spawn errors
- remove the address() guard; 'listening' does not fire on a failed bind
This commit is contained in:
Sampson authored and GitHub committed 2026-09-17 07:45:23 -07:00
1 parent 2cf96460c1
commit 50cb919200
21 files changed
+191 -252

No files matched your search

+18 -8
View File
@@ -394,29 +394,39 @@ Add a reference to your local build in `claude_desktop_config.json`:
### Testing via MCP Inspector
1. Build and start the server:
The Inspector requires Node 22.19 or newer.
**STDIO** — the Inspector launches the server itself, so one terminal is enough:
```bash
npm run build
node dist/index.js
```
2. In another terminal, start the MCP Inspector:
```bash
npx @modelcontextprotocol/inspector node dist/index.js
```
STDIO is the default mode. For HTTP mode testing, add `--transport http` to the arguments in the Inspector UI.
**HTTP** — the Inspector connects to a URL, so the server must already be listening:
```bash
# terminal 1
npm run serve:http
# terminal 2
npm run inspector:http
```
`serve:http` builds, binds `127.0.0.1:8080`, and reads `BRAVE_API_KEY` from `.env`.
### Available Scripts
- `npm run build`: Build the TypeScript project
- `npm run watch`: Watch for changes and rebuild
- `npm test`: Run the test suite
- `npm run format`: Format code with Prettier
- `npm run format:check`: Check code formatting
- `npm run prepare`: Format and build (runs automatically on npm install)
- `npm run serve:http`: Build, then serve over HTTP at `http://127.0.0.1:8080/mcp`
- `npm run inspector`: Launch an instance of MCP Inspector
- `npm run inspector:stdio`: Launch a instance of MCP Inspector, configured for STDIO
- `npm run inspector:http`: Launch MCP Inspector against `http://127.0.0.1:8080/mcp`
### Docker Compose
+3 -2
View File
@@ -26,14 +26,15 @@
"dist"
],
"scripts": {
"build": "tsc && shx chmod +x dist/*.js",
"build": "shx rm -rf dist && tsc && shx chmod +x dist/*.js",
"prepare": "npm run format && npm run build",
"watch": "tsc --watch",
"format": "prettier --write \"src/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\"",
"test": "node --import tsx --test \"src/**/*.test.ts\"",
"serve:http": "npm run build && node dist/index.js --transport http",
"inspector": "npx @modelcontextprotocol/inspector",
"inspector:http": "npx @modelcontextprotocol/inspector --transport http"
"inspector:http": "npx @modelcontextprotocol/inspector --transport http --server-url http://127.0.0.1:8080/mcp"
},
"dependencies": {
"@modelcontextprotocol/sdk": "1.30.0",
+2 -3
View File
@@ -46,8 +46,7 @@ async function issueRequest<T extends keyof Endpoints>(
parameters: Endpoints[T]['params'],
requestHeaders: Endpoints[T]['requestHeaders'] = {} as Endpoints[T]['requestHeaders']
): Promise<Endpoints[T]['response']> {
// TODO (Sampson): Improve rate-limit logic to support self-throttling and n-keys
// checkRateLimit();
// TODO (Sampson): Add rate-limit logic supporting self-throttling and n-keys
// Determine URL, and setup parameters
const url = new URL(`https://api.search.brave.com${typeToPathMap[endpoint]}`);
@@ -123,7 +122,7 @@ async function issueRequest<T extends keyof Endpoints>(
try {
const responseBody = await response.json();
errorMessage += `\n${stringify(responseBody, true)}`;
} catch (error) {
} catch {
errorMessage += `\n${await response.text()}`;
}
-19
View File
@@ -21,25 +21,6 @@ import type {
} from '../tools/place_search/schemas/input.js';
import type { PlaceSearchApiResponse } from '../tools/place_search/schemas/output.js';
export interface RateLimitErrorResponse {
type: 'ErrorResponse';
error: {
id: string;
status: number;
code: 'RATE_LIMITED';
detail: string;
meta: {
plan: string;
rate_limit: number;
rate_current: number;
quota_limit: number;
quota_current: number;
component: 'rate_limiter';
};
};
time: number;
}
export type Endpoints = {
web: {
params: WebQueryParams;
-4
View File
@@ -1,4 +0,0 @@
export const RATE_LIMIT = {
perSecond: 1,
perMonth: 15000,
} as const;
-16
View File
@@ -1,16 +0,0 @@
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
export function registerSigIntHandler(
transports: Map<string, StdioServerTransport | StreamableHTTPServerTransport>
) {
process.on('SIGINT', async () => {
for (const sessionID of transports.keys()) {
await transports.get(sessionID)?.close();
transports.delete(sessionID);
}
console.error('Server shut down.');
process.exit(0);
});
}
+1 -1
View File
@@ -11,7 +11,7 @@ import tools from './tools/index.js';
* The dialect servers MUST emit by default, per SEP-1613 §5.
* https://modelcontextprotocol.io/seps/1613-establish-json-schema-2020-12-as-default-dialect-f
*/
export const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
type ToolSchemaShapes = {
inputSchema?: ZodRawShape;
+73 -1
View File
@@ -1,7 +1,9 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import http, { type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import net, { type AddressInfo } from 'node:net';
import { after, before, describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import config from '../config.js';
import httpServer from './http.js';
@@ -214,3 +216,73 @@ describe('http Host validation (opt-in)', () => {
assert.equal(res.status, 403);
});
});
const entrypoint = fileURLToPath(new URL('../index.ts', import.meta.url));
const STARTUP_HOST = '127.0.0.1';
const EXIT_TIMEOUT_MS = 15_000;
// `start()` exits the process on a bind failure, so drive it from a child.
// The host is pinned to match the blocker, since BRAVE_MCP_HOST would otherwise
// send the child to a different interface and let it bind.
const startServer = (port: number): Promise<{ code: number | null; out: string; err: string }> => {
const child = spawn(
process.execPath,
[
'--import',
'tsx',
entrypoint,
'--transport',
'http',
'--host',
STARTUP_HOST,
'--port',
String(port),
],
{ env: { ...process.env, BRAVE_API_KEY: 'test-key' } }
);
let out = '';
let err = '';
child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString()));
child.stderr.on('data', (chunk: Buffer) => (err += chunk.toString()));
return new Promise((resolve, reject) => {
// A child that never exits is the regression under test; fail rather than hang.
const timer = setTimeout(() => {
child.kill();
reject(new Error(`Server did not exit within ${EXIT_TIMEOUT_MS}ms.\n${out}\n${err}`));
}, EXIT_TIMEOUT_MS);
child.on('error', (error) => {
clearTimeout(timer);
reject(error);
});
child.on('exit', (code) => {
clearTimeout(timer);
resolve({ code, out, err });
});
});
};
describe('HTTP transport startup', () => {
let blocker: net.Server;
let takenPort: number;
before(async () => {
blocker = net.createServer();
await new Promise<void>((resolve) => blocker.listen(0, STARTUP_HOST, () => resolve()));
takenPort = (blocker.address() as AddressInfo).port;
});
after(() => new Promise<void>((resolve) => blocker.close(() => resolve())));
it('exits with an error when the port is already in use', async () => {
const { code, out, err } = await startServer(takenPort);
assert.equal(code, 1, err);
assert.match(err, /already in use/);
assert.doesNotMatch(out, /Server is running/);
});
});
+9 -1
View File
@@ -99,10 +99,18 @@ const start = () => {
}
const app = createApp();
const server = app.listen(config.port, config.host);
app.listen(config.port, config.host, () => {
server.on('listening', () => {
console.log(`Server is running on http://${config.host}:${config.port}/mcp`);
});
server.on('error', (error: NodeJS.ErrnoException) => {
const detail =
error.code === 'EADDRINUSE' ? `port ${config.port} is already in use` : error.message;
console.error(`Unable to start HTTP server: ${detail}`);
process.exit(1);
});
};
export default { start, createApp };
+59
View File
@@ -0,0 +1,59 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import {
StdioClientTransport,
getDefaultEnvironment,
} from '@modelcontextprotocol/sdk/client/stdio.js';
import tools from '../tools/index.js';
const entrypoint = fileURLToPath(new URL('../index.ts', import.meta.url));
/**
* Spawns the real CLI over stdio, covering argument parsing, server wiring, and
* JSON-RPC framing. Runs the source through tsx, so `npm test` needs no build.
*
* `tools/list` keeps this hermetic: it reaches the API client without issuing a
* request.
*/
describe('stdio transport (real child process)', () => {
let client: Client;
let transport: StdioClientTransport;
let stderr = '';
before(async () => {
transport = new StdioClientTransport({
command: process.execPath,
args: ['--import', 'tsx', entrypoint],
// Startup requires a key.
env: { ...getDefaultEnvironment(), BRAVE_API_KEY: 'test-key' },
stderr: 'pipe',
});
transport.stderr?.on('data', (chunk: Buffer) => {
stderr += chunk.toString();
});
client = new Client({ name: 'stdio-test-client', version: '0.0.0' });
await client.connect(transport);
});
after(async () => {
await client.close();
});
it('serves the registered tools over stdin/stdout', async () => {
const { tools: listedTools } = await client.listTools();
// Both sides read the same registry; guard against an empty one.
assert.ok(listedTools.length > 0, stderr);
assert.deepEqual(
listedTools.map((tool) => tool.name).sort(),
Object.values(tools)
.map((tool) => tool.name)
.sort(),
stderr
);
});
});
+2 -6
View File
@@ -1,14 +1,10 @@
import newMcpServer from '../server.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const createTransport = (): StdioServerTransport => {
return new StdioServerTransport();
};
const start = async (): Promise<void> => {
const transport = createTransport();
const transport = new StdioServerTransport();
const mcpServer = newMcpServer();
await mcpServer.connect(transport);
};
export default { start, createTransport };
export default { start };
+2 -3
View File
@@ -7,13 +7,12 @@ import tools from './tools/index.js';
describe('MCP server <-> SDK Client wiring (in-memory)', () => {
let client: Client;
let close: () => Promise<void>;
before(async () => {
({ client, close } = await connectTestClient());
client = await connectTestClient();
});
after(() => close());
after(() => client.close());
it('lists every registered tool with a valid input schema', async () => {
const { tools: listedTools } = await client.listTools();
+8 -11
View File
@@ -5,27 +5,25 @@ import createMcpServer from '../server.js';
/**
* Connects a real SDK Client to a fresh McpServer over an in-memory transport
* pair, so tests exercise the actual registerTool/callTool wiring instead of
* invoking a tool's `execute` function directly.
* pair, exercising the real registerTool/callTool wiring.
*
* Tear down with `client.close()`; it cascades to the server.
*/
export async function connectTestClient(): Promise<{
client: Client;
close: () => Promise<void>;
}> {
export async function connectTestClient(): Promise<Client> {
const mcpServer = createMcpServer();
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'test-client', version: '0.0.0' });
await Promise.all([mcpServer.connect(serverTransport), client.connect(clientTransport)]);
return { client, close: () => client.close() };
return client;
}
/**
* Replaces global.fetch with a stub that resolves requests via `handler`,
* keyed on the request's pathname. Returns a restore function.
*/
export function stubFetch(handler: (url: URL) => unknown): () => void {
function stubFetch(handler: (url: URL) => unknown): () => void {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
@@ -54,17 +52,16 @@ export function stubFetch(handler: (url: URL) => unknown): () => void {
*/
export function useTestClient(responder: (url: URL) => unknown): () => Client {
let client: Client;
let close: () => Promise<void>;
let restoreFetch: () => void;
before(async () => {
restoreFetch = stubFetch(responder);
({ client, close } = await connectTestClient());
client = await connectTestClient();
});
after(async () => {
restoreFetch();
await close();
await client.close();
});
return () => client;
-52
View File
@@ -4,62 +4,10 @@ import { z } from 'zod';
* https://api-dashboard.search.brave.com/app/documentation/image-search/responses
*/
const QuerySchema = z.object({
original: z.string().describe('The original query string.'),
altered: z.string().optional().describe('The altered query string.'),
spellcheck_off: z.boolean().optional().describe('Whether spellcheck was disabled.'),
show_strict_warning: z
.boolean()
.optional()
.describe('When true, some results were blocked by safesearch.'),
});
const ThumbnailSchema = z.object({
src: z.url().optional().describe('The URL of the thumbnail.'),
width: z.int().positive().optional().describe('The width of the thumbnail.'),
height: z.int().positive().optional().describe('The height of the thumbnail.'),
});
const PropertiesSchema = z.object({
url: z.url().optional().describe('The URL of the image.'),
placeholder: z.url().optional().describe('The lower resolution placeholder image.'),
width: z.int().positive().optional().describe('The width of the image.'),
height: z.int().positive().optional().describe('The height of the image.'),
});
const MetaUrlSchema = z.object({
scheme: z.enum(['https', 'http']).optional().describe('The scheme of the URL.'),
netloc: z.string().optional().describe('The network location of the URL.'),
hostname: z.string().optional().describe('The lowercased hostname of the URL.'),
favicon: z.url().optional().describe('The URL of the favicon of the URL.'),
path: z.string().optional().describe('The path of the URL (useful as a display string).'),
});
export const ConfidenceSchema = z
.enum(['low', 'medium', 'high'])
.describe('The confidence level of the result.');
const ImageResultSchema = z.object({
type: z.literal('image_result').describe('The type of result.'),
title: z.string().optional().describe('The title of the image.'),
url: z.url().optional().describe('The URL of the image.'),
source: z.url().optional().describe('The source URL of the image.'),
page_fetched: z.iso.datetime().optional().describe('The date and time the page was fetched.'),
thumbnail: ThumbnailSchema.optional().describe('The thumbnail of the image.'),
properties: PropertiesSchema.optional().describe('The metadata for the image.'),
meta_url: MetaUrlSchema.optional().describe(
'Information about the URL associated with the image.'
),
confidence: ConfidenceSchema.optional(),
});
export const ExtraSchema = z.object({
might_be_offensive: z.boolean().describe('Whether the image might be offensive.'),
});
export const ImageSearchApiResponseSchema = z.object({
type: z.literal('images').describe('The type of API response.'),
query: QuerySchema.describe('The query used to generate the results.'),
results: z.array(ImageResultSchema).describe('The results of the image search.'),
extra: ExtraSchema.describe('Extra information about the search.'),
});
+1 -1
View File
@@ -50,7 +50,7 @@ interface Thumbnail {
height?: number;
}
export interface Properties {
interface Properties {
/** The image URL. */
url?: string;
/** The lower resolution placeholder image URL. */
+3 -3
View File
@@ -86,9 +86,9 @@ export const register = (mcpServer: McpServer) => {
);
};
const buildFallbackWebResponse = (web_fallback: WebSearchApiResponse['web']): CallToolResult => {
if (!web_fallback || web_fallback.results.length === 0) throw new Error('No web results found');
const buildFallbackWebResponse = (
web_fallback: NonNullable<WebSearchApiResponse['web']>
): CallToolResult => {
const fallback = {
content: [
{
+2 -2
View File
@@ -56,7 +56,7 @@ export const execute = async (params: SummarizerQueryParams) => {
text: summaryText,
});
}
} catch (error) {
} catch {
response.isError = true;
response.content.push({
type: 'text' as const,
@@ -93,7 +93,7 @@ const pollForSummary = async (
if (response.status === 'complete') {
result = response;
}
} catch (error) {
} catch {
await new Promise((resolve) => setTimeout(resolve, pollInterval));
}
-64
View File
@@ -17,67 +17,3 @@ export const summarizerQueryParams = z.object({
});
export type SummarizerQueryParams = z.infer<typeof summarizerQueryParams>;
export const chatCompletionsMessage = z.object({
role: z
.enum(['user'])
.default('user')
.describe('The role of the message. Only "user" is supported for now.'),
content: z
.string()
.describe('The content of the message. The value is the question to be answered.'),
});
export type ChatCompletionsMessage = z.infer<typeof chatCompletionsMessage>;
export const chatCompletionParams = z.object({
messages: z
.array(chatCompletionsMessage)
.describe(
'The messages to use for the chat completion. The value is a list of ChatCompletionsMessage response models.'
),
model: z
.enum(['brave-pro', 'brave'])
.default('brave-pro')
.optional()
.describe(
'The model to use for the chat completion. The value can be "brave-pro" (default) or "brave".'
),
stream: z
.boolean()
.default(true)
.optional()
.describe(
'Whether to stream the response. The value is `true` by default. When using the OpenAI CLI, use `openai.AsyncOpenAI` for streaming and `openai.OpenAI` for blocking mode.'
),
country: z
.string()
.default('us')
.optional()
.describe(
'The country backend to use for the chat completion. The value is "us" by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
),
language: z
.string()
.default('en')
.optional()
.describe(
'The language to use for the chat completion. The value is "en" by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
),
enable_entities: z
.boolean()
.default(false)
.optional()
.describe(
'Whether to enable entities in the chat completion. The value is `false` by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
),
enable_citations: z
.boolean()
.default(false)
.optional()
.describe(
'Whether to enable citations in the chat completion. The value is `false` by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
),
});
export type ChatCompletionParams = z.infer<typeof chatCompletionParams>;
+5 -7
View File
@@ -63,13 +63,11 @@ export const execute = async (params: QueryParams) => {
}
// TODO (Sampson): The following is unnecessarily repetitive.
if (web && web.results?.length > 0) {
for (const entry of formatWebResults(web)) {
response.content.push({
type: 'text' as const,
text: stringify(entry),
});
}
for (const entry of formatWebResults(web)) {
response.content.push({
type: 'text' as const,
text: stringify(entry),
});
}
if (faq && faq.results?.length > 0) {
+2 -25
View File
@@ -71,20 +71,6 @@ export interface WebSearchApiResponse {
rich?: RichCallbackInfo;
}
export interface LocalPoiSearchApiResponse {
/** The type of local POI search API result. The value is always local_pois. */
type: 'local_pois';
/** Location results matching the ids in the request. */
results?: LocationResult[];
}
export interface LocalDescriptionsSearchApiResponse {
/** The type of local description search API result. The value is always local_descriptions. */
type: 'local_descriptions';
/** Location descriptions matching the ids in the request. */
results?: LocationDescription[];
}
interface Query {
/** The original query that was requested. */
original: string;
@@ -154,7 +140,7 @@ interface DiscussionResult extends Omit<SearchResult, 'type'> {
data?: ForumData;
}
export interface ForumData {
interface ForumData {
/** The name of the forum. */
forum_name: string;
/** The number of answers to the post. */
@@ -211,7 +197,7 @@ export interface Search {
family_friendly: boolean;
}
export interface SearchResult extends Result {
interface SearchResult extends Result {
/** A type identifying a web search result. The value is always search_result. */
type: 'search_result';
/** A sub type identifying the web search result type. */
@@ -449,15 +435,6 @@ interface LocationResult extends Result {
timezone_offset?: number;
}
interface LocationDescription {
/** The type of a location description. The value is always local_description. */
type: 'local_description';
/** A Temporary id of the location with this description. */
id: string;
/** AI generated description of the location with the given id. */
description?: string;
}
interface Locations {
/** Location type identifier. The value is always locations. */
type: 'locations';
+1 -23
View File
@@ -1,32 +1,10 @@
import { readFileSync } from 'node:fs';
import { RATE_LIMIT } from './constants.js';
let requestCount = {
second: 0,
month: 0,
lastReset: Date.now(),
};
export function checkRateLimit() {
const now = Date.now();
if (now - requestCount.lastReset > 1000) {
requestCount.second = 0;
requestCount.lastReset = now;
}
if (requestCount.second >= RATE_LIMIT.perSecond || requestCount.month >= RATE_LIMIT.perMonth) {
throw new Error('Rate limit exceeded');
}
requestCount.second++;
requestCount.month++;
}
export function stringify(data: any, pretty = false) {
return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
}
export type ReadBraveApiKeyFromFileResult =
| { ok: true; key: string }
| { ok: false; error: string };
type ReadBraveApiKeyFromFileResult = { ok: true; key: string } | { ok: false; error: string };
export function readBraveApiKeyFromFile(filePath: string): ReadBraveApiKeyFromFileResult {
try {