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_TOKEN is required with --http and is read from the environment only (a command-line value would be visible in the process list). It must be at least 32 characters of A-Z a-z 0-9 - . _ ~ + /, optionally followed by = padding; openssl rand -base64 32 produces one. An absent, short or malformed value refuses the start.
  • Every request needs it, /health included, as Authorization: Bearer <secret>; without the exact secret the answer is 401 and nothing runs. A health probe that cannot send a header can use a TCP check; a Kubernetes httpGet probe can send it with httpHeaders.
  • 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> (or TOPGUN_MCP_HOST) takes an IP address, not a name; an address other than 127.0.0.0/8 or ::1 also needs --allow-public-bind (or TOPGUN_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 Origin header gets 403 unless that origin is allowlisted; a request without the secret gets the same 401 whatever its Origin. The command line allowlists none, on purpose; a browser deployment passes corsOrigins to HTTPTransport (below). * is refused.
  • What it serves. POST /mcp with tools/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_PORT that 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):

FieldDefaultDescription
name"topgun-mcp-server"Server name advertised over MCP.
version"1.0.0"Server version.
topgunUrl"ws://localhost:8080"TopGun WebSocket URL.
authTokennoneJWT passed to client.setAuthToken().
allowedMapsunrestrictedWhitelist of map names the assistant may touch.
enableMutationstrueIf false, topgun_mutate returns an error.
enableSubscriptionstrueIf false, topgun_subscribe is unavailable.
defaultLimit10Default page size for topgun_query.
maxLimit100Hard cap on requested page size.
subscriptionTimeoutSeconds60Default idle lifetime of a topgun_subscribe feed; auto-stops after this long without a poll (refreshed on each poll).
debugfalseVerbose logging.
clientnonePre-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 allowedMaps when 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 when hasMore is true
  • Security: rejects maps outside allowedMaps; clamps limit to maxLimit
> 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 outside allowedMaps
> Add a task: "Write the spec response"
[runs topgun_mutate with op: 'create', value: { text: '...', done: false }]

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 a subscriptionId as soon as the server confirms the watch (it does not hold the call open for the watch window). filter is field equality, as in topgun_query: with filter: { status: 'open' } the feed reports only changes to records whose status equals '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 to subscriptionTimeoutSeconds); 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:

TunableBehavior
allowedMapsHard whitelist. Tools refuse to operate on maps outside the list.
enableMutationsWhen false, topgun_mutate returns an error before touching the database.
enableSubscriptionsWhen 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.


← Server & CLI · Protocol →