MCP
@topgunbuild/mcp-server lets AI assistants read and mutate your TopGun data through the Model Context Protocol. Drop it into Claude Desktop, Cursor, or any MCP-compatible client and the assistant gains eight tools for querying, mutating, searching, and inspecting your maps.
For the broader story (how to design schemas the model can use, prompting patterns), see the Building with AI guide.
Installation and transport
The server ships as @topgunbuild/mcp-server on npm and runs over either stdio (default) or HTTP.
Stdio (Claude Desktop, Cursor)
The server starts when the host AI client spawns it. No long-running process required.
Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"topgun": {
"command": "npx",
"args": ["@topgunbuild/mcp-server"],
"env": {
"TOPGUN_URL": "ws://localhost:8080"
}
}
}
}
Cursor (~/.cursor/mcp.json):
{
"mcp": {
"servers": {
"topgun": {
"command": "npx",
"args": ["@topgunbuild/mcp-server"],
"env": {
"TOPGUN_URL": "ws://localhost:8080"
}
}
}
}
}
HTTP
For remote MCP clients or shared deployments, run the server as a long-lived HTTP service. Every request must carry a
secret you choose, the server listens on 127.0.0.1 unless you allow more, and browsers on other origins are refused.
# The secret every HTTP request must send; at least 32 characters
export TOPGUN_MCP_HTTP_TOKEN=$(openssl rand -base64 32)
# Default: 127.0.0.1, port 3000
npx @topgunbuild/mcp-server --http --port 3000
# With auth, restricted maps, mutations disabled
npx @topgunbuild/mcp-server --http --port 3000 \
--url ws://production.example.com:8080 \
--token $TOPGUN_TOKEN \
--maps tasks,users \
--no-mutations
- Secret.
TOPGUN_MCP_HTTP_TOKENis required with--httpand is read from the environment only (a command-line value would be visible in the process list). It must be at least 32 characters ofA-Z a-z 0-9 - . _ ~ + /, optionally followed by=padding;openssl rand -base64 32produces one. An absent, short or malformed value refuses the start. - Every request needs it,
/healthincluded, asAuthorization: Bearer <secret>; without the exact secret the answer is401and nothing runs. A health probe that cannot send a header can use a TCP check; a KuberneteshttpGetprobe can send it withhttpHeaders. - What the secret grants. Every holder of the secret acts as the TopGun identity of
--token/TOPGUN_TOKEN: the tools run with that identity’s permissions. A separate identity per HTTP caller is not yet supported. - Bind address. The server binds
127.0.0.1.--host <ip>(orTOPGUN_MCP_HOST) takes an IP address, not a name; an address other than127.0.0.0/8or::1also needs--allow-public-bind(orTOPGUN_MCP_ALLOW_PUBLIC_BIND=1), and the server then logs a warning at start. The transport speaks plain HTTP, so the secret travels in clear: put TLS in front of it when it is reachable from the network. - Browsers. An authenticated request carrying an
Originheader gets403unless that origin is allowlisted; a request without the secret gets the same401whatever itsOrigin. The command line allowlists none, on purpose; a browser deployment passescorsOriginstoHTTPTransport(below).*is refused. - What it serves.
POST /mcpwithtools/call; other MCP methods, and SSE sessions, are not supported over HTTP. - Refused starts. An unsafe or malformed setting — the secret, the host, or a
--port/TOPGUN_MCP_PORTthat is not an integer from 1 to 65535 — exits with code 1 and one line on stderr,topgun-mcp: refusing to start: ….
To serve HTTP from your own process, construct the transport and start it with the server:
import { HTTPTransport, TopGunMCPServer } from '@topgunbuild/mcp-server';
const server = new TopGunMCPServer({ topgunUrl: 'ws://localhost:8080' });
const http = new HTTPTransport({
port: 3000,
bearerToken: process.env.TOPGUN_MCP_HTTP_TOKEN!,
// Optional: browser origins allowed to call it; '*' is refused.
corsOrigins: ['https://app.example.com'],
});
await http.start(server);
The constructor throws HTTPTransportConfigError (with a field naming the setting) on a missing or malformed
bearerToken, a port that is not an integer from 1 to 65535, a hostname or a non-loopback host without
allowPublicBind: true, and a corsOrigins entry that is * or not a serialized origin of the form
scheme://host[:port] (no path, no trailing slash, no default port such as :443).
Programmatic API
For embedding the MCP server inside an existing Node process, use the TopGunMCPServer class.
import { TopGunMCPServer } from '@topgunbuild/mcp-server';
const server = new TopGunMCPServer({
topgunUrl: 'ws://localhost:8080',
authToken: process.env.TOPGUN_TOKEN,
allowedMaps: ['tasks', 'users', 'projects'],
enableMutations: true,
enableSubscriptions: true,
defaultLimit: 10,
maxLimit: 100,
debug: false,
});
await server.start();
MCPServerConfig fields (all optional):
| Field | Default | Description |
|---|---|---|
name | "topgun-mcp-server" | Server name advertised over MCP. |
version | "1.0.0" | Server version. |
topgunUrl | "ws://localhost:8080" | TopGun WebSocket URL. |
authToken | none | JWT passed to client.setAuthToken(). |
allowedMaps | unrestricted | Whitelist of map names the assistant may touch. |
enableMutations | true | If false, topgun_mutate returns an error. |
enableSubscriptions | true | If false, topgun_subscribe is unavailable. |
defaultLimit | 10 | Default page size for topgun_query. |
maxLimit | 100 | Hard cap on requested page size. |
subscriptionTimeoutSeconds | 60 | Default idle lifetime of a topgun_subscribe feed; auto-stops after this long without a poll (refreshed on each poll). |
debug | false | Verbose logging. |
client | none | Pre-built TopGunClient instance (overrides topgunUrl + authToken). |
server.start() serves stdio and registers tool handlers; for HTTP, construct HTTPTransport and call start(server) (see HTTP).
Tools
The server exposes eight tools, all prefixed with topgun_. The assistant chooses which to invoke based on the natural-language prompt.
topgun_list_maps
List every map the server knows about.
- Parameters: none
- Response: array of
{ name, recordCount, hasFTS, hasVectorIndex } - Security: filtered by
allowedMapswhen set
> What maps are available?
[lists tasks, users, projects]
topgun_query
Read records from a map with filters and sorting. Returns authoritative server data — the assistant gets the live, server-confirmed answer, not a stale local guess.
- Parameters:
{ map, filter?, sort?, limit?, fields?, cursor? } - Response:
[{ _key, ...fields }](a settled array) with an optional continuation note whenhasMoreis true - Security: rejects maps outside
allowedMaps; clampslimittomaxLimit
> Show me unfinished tasks created this week
[runs topgun_query with filter: { done: false }]
A settled result with no matching records renders as No results found in map '<map>'... — that means the server genuinely has no such rows, not that the query failed.
Offline / not-settled behavior. topgun_query never silently returns stale local data and never conflates “offline” with “empty”. If the server cannot be reached, or the query does not settle within the default 5000 ms window, the tool returns an error (isError: true) explaining that no authoritative data was returned — so the assistant knows to retry rather than reporting an empty list. The message distinguishes the two causes (server unreachable / client offline, vs. timed out waiting for the server).
Cursor pagination. When the server has more results than the returned limit, the response includes a cursor token and appends a continuation note: “To fetch the next page, call this tool again with cursor: <value>.” Pass that token as the optional cursor parameter on the next call to receive the following page. Repeat until hasMore is false (no continuation note appears). This lets an agent walk through a large result set page by page without re-fetching rows it has already seen.
If you do not need further pages, the continuation note also tells you to narrow with filter / sort or raise limit (up to maxLimit) — useful when you want a different slice rather than sequential pages.
A settled result with no matching records renders as No results found in map '<map>'... — that means the server genuinely has no such rows, not that the query failed.
topgun_mutate
Create, update, or remove a record.
- Parameters:
{ map, op: "create" | "update" | "remove", key, value? } - Response:
{ success, key }or an error object - Security: requires
enableMutations: true; rejects maps outsideallowedMaps
> Add a task: "Write the spec response"
[runs topgun_mutate with op: 'create', value: { text: '...', done: false }]
topgun_search
BM25 full-text search across a map.
- Parameters:
{ map, query, limit?, minScore?, boost? } - Response:
[{ _key, value, score, matchedTerms }] - Note: the server indexes every map for full-text search by default — no per-map opt-in needed
> Find tasks mentioning "deployment"
[runs topgun_search with query: 'deployment']
topgun_subscribe
Watch a map for real-time changes via a poll cursor. MCP is a request/response
protocol, so a tool call cannot stream changes into the assistant’s turn; instead the
feed is drained on demand. Each reported change is a genuine, typed delta (add /
update / remove) — removals are first-class, and the existing snapshot is never
re-reported as “changes”.
- Parameters:
{ action: 'start' | 'poll' | 'stop' | 'list', map?, filter?, subscriptionId?, ttlSeconds? } - Usage:
action: 'start'{ map, filter? }— opens a server-backed live query and returns asubscriptionIdas soon as the server confirms the watch (it does not hold the call open for the watch window).filteris field equality, as intopgun_query: withfilter: { status: 'open' }the feed reports only changes to records whosestatusequals'open', and a record that stops matching is reported as a remove. Errors if the server cannot deliver an initial baseline (offline / unreachable).action: 'poll'{ subscriptionId }— returns the changes observed since the last poll as{ type, key, value? }. Refreshes the subscription’s idle timer. Reports if the buffer overflowed (changes dropped).action: 'stop'{ subscriptionId }— ends the subscription.action: 'list'— shows active subscriptions.
- Lifetime: an unpolled subscription auto-stops after
ttlSeconds(defaults tosubscriptionTimeoutSeconds); each poll refreshes it. - Security: requires
enableSubscriptions: true
topgun_schema
Inspect a map’s schema (registered field types, indexes, FTS configuration).
- Parameters:
{ map } - Response:
{ name, fields, indexes, fts?, vectorIndex? }
topgun_stats
Operational stats for a map.
- Parameters:
{ map } - Response:
{ recordCount, sizeBytes, tombstoneCount, ftsIndexSize?, vectorIndexSize? }
topgun_explain
Show the query plan and estimated cost for a query without executing it.
- Parameters:
{ map, filter?, sort?, limit? } - Response:
{ plan: PlanStep[], estimatedCost, indexesUsed }
Use this to debug why a query is slow or to confirm the planner is picking the index you expect.
Security model
Three tunables shape what the assistant can do:
| Tunable | Behavior |
|---|---|
allowedMaps | Hard whitelist. Tools refuse to operate on maps outside the list. |
enableMutations | When false, topgun_mutate returns an error before touching the database. |
enableSubscriptions | When false, topgun_subscribe is unavailable. |
For production deployments, run the MCP server with a service-scoped JWT (via authToken) so the underlying TopGun server’s authorization policies are also enforced. The MCP layer is defense-in-depth, not a substitute for proper server-side auth.