GebSecure Docs v0.1.0

Get started

Quickstart: secure an MCP server

Put an MCP server behind the GebSecure MCP gateway, authorize its tools with policy and connect a client.

MCP clients connect to the GebSecure gateway instead of directly to MCP servers. Every tools/call runs the full pipeline — argument validation against the pinned schema, outbound DLP, authorization and risk, approval, the upstream call with credentials injected by the broker, sanitization, inbound DLP, prompt-injection inspection and audit. The snippets on this page are the files in docs/site/snippets/mcp, which the documentation test suite runs against a real gateway.

1. Start an MCP server#

Any MCP server reachable over Streamable HTTP works. To follow along, start the demo server, which has a read-only get_forecast tool and a destructive delete_note tool:

bash
npx tsx docs/site/snippets/mcp/demo-server.ts        # http://127.0.0.1:4310/mcp
docs/site/snippets/mcp/demo-server.ts
const TOOLS = [
  {
    name: 'get_forecast',
    description: 'Weather forecast for a city',
    inputSchema: { type: 'object', required: ['city'], properties: { city: { type: 'string', maxLength: 100 } }, additionalProperties: false },
    annotations: { readOnlyHint: true },
  },
  {
    name: 'delete_note',
    description: 'Deletes a note by id',
    inputSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } }, additionalProperties: false },
    annotations: { destructiveHint: true },
  },
];

GebSecure reaches upstream servers through its SSRF-safe broker: HTTPS only and public addresses only, except in development, where plain HTTP is allowed and EXECUTION_ALLOW_PRIVATE_NETWORKS=true lets it reach 127.0.0.1.

2. Register the server#

Registering requires the mcp:manage permission. The request is POST {api}/v1/mcp/servers:

docs/site/snippets/mcp/register.ts
// Register the upstream MCP server. Agents will reach it as {gateway}/v1/mcp/demo. Tool definitions are
// discovered, scanned for poisoning and pinned by hash on first use.
const server = await api<{ id: string; slug: string }>('POST', '/v1/mcp/servers', {
  projectId: project.id,
  environmentId: environment.id,
  slug: 'demo',
  name: 'Demo MCP server',
  url: process.env.MCP_SERVER_URL ?? 'http://127.0.0.1:4310/mcp',
  authType: 'none', // 'bearer' | 'api_key' | 'oauth2' take a vault secretId; the agent never sees it
  requirePinning: true,
  rateLimitPerMinute: 120,
});
Field Meaning
slug ^[a-z0-9][a-z0-9-]{0,40}$; agents reach the server at {gateway}/v1/mcp/{slug} and policies name its tools mcp:{slug}/{tool}
url the upstream Streamable HTTP endpoint (validated against SSRF rules)
authType, secretId, authHeader none, bearer, api_key (header authHeader, default x-api-key) or oauth2; the credential is a vault secret, never visible to agents
allowedTools, deniedTools glob patterns restricting which tools are exposed
requirePinning default true: a tool whose definition changes is quarantined until an administrator re-approves it
rateLimitPerMinute per agent and server, default 120

3. Write the policy#

Tool calls are authorized like any other action, as mcp:<slug>/<tool>. Default deny applies: a tool without a permit is denied.

docs/site/snippets/mcp/policy.gsl
# MCP tool calls are authorized as action and resource "mcp:<server slug>/<tool>".
policy "mcp-demo-forecast" {
  description "Agents may read forecasts through the demo MCP server"
  effect permit
  principal agent
  action "mcp:demo/get_forecast"
  resource any
}

policy "mcp-demo-delete-notes" {
  description "Deleting notes needs an owner's approval"
  effect permit
  principal agent
  action "mcp:demo/delete_note"
  resource any
  require approval {
    approvers role "owner"
    expires 30m
  }
}
docs/site/snippets/mcp/register.ts
const source = fs.readFileSync(new URL('./policy.gsl', import.meta.url), 'utf8');
const policy = await admin.createPolicy({ name: `mcp-demo-${Date.now()}`, source, scope: { type: 'environment', environmentId: environment.id } });
const deployed = await admin.deployPolicy(policy.id, { versionId: policy.versionId, comment: 'MCP quickstart' });
if (!deployed.deployed) throw new Error('policy deployment blocked');

4. Give the agent credentials#

Agents need the mcp:connect permission, which agent principals have. The quickstart registers one:

docs/site/snippets/mcp/register.ts
const agent = await admin.createAgent({ environmentId: environment.id, name: `mcp-demo-agent-${Date.now()}`, framework: 'mcp', credential: { type: 'client_secret', name: 'mcp' } });

Run the whole setup as an administrator:

bash
export GEBSECURE_ADMIN_EMAIL=admin@gebsecure.local GEBSECURE_ADMIN_PASSWORD='<password from npm run setup>'
export MCP_SERVER_URL=http://127.0.0.1:4310/mcp
eval "$(npx tsx --tsconfig docs/site/snippets/tsconfig.json docs/site/snippets/mcp/register.ts)"

5. Connect a client#

The gateway speaks the MCP Streamable HTTP transport (protocol 2025-06-18; 2025-03-26 and 2024-11-05 are accepted). Authenticate with the agent's GebSecure access token — or an API key — in the Authorization header, call initialize, then send the returned Mcp-Session-Id header with every later request:

docs/site/snippets/mcp/client.ts
const gs = new GebSecure(); // GEBSECURE_CLIENT_SECRET → short-lived access tokens (cached, refreshed)
const endpoint = `${gs.gatewayUrl}/v1/mcp/${process.env.MCP_SERVER_SLUG ?? 'demo'}`; // or /v1/mcp for every server
let sessionId: string | undefined;

interface RpcResponse {
  result?: { content?: { type: string; text?: string }[]; isError?: boolean; tools?: { name: string }[]; _meta?: { gebsecure?: Record<string, unknown> } };
  error?: { code: number; message: string };
}

async function rpc(method: string, params: Record<string, unknown> = {}): Promise<RpcResponse> {
  const res = await fetch(endpoint, {
    method: 'POST',
    headers: {
      authorization: `Bearer ${await gs.getAccessToken()}`,
      'content-type': 'application/json',
      accept: 'application/json, text/event-stream',
      ...(sessionId ? { 'mcp-session-id': sessionId } : {}),
    },
    body: JSON.stringify({ jsonrpc: '2.0', id: randomUUID(), method, params }),
  });
  if (!res.ok) throw new Error(`${method} → HTTP ${res.status}: ${await res.text()}`);
  if (method === 'initialize') sessionId = res.headers.get('mcp-session-id') ?? undefined;
  return (await res.json()) as RpcResponse;
}

const init = await rpc('initialize', { protocolVersion: '2025-06-18', clientInfo: { name: 'quickstart', version: '1.0.0' }, capabilities: {} });
if (init.error) throw new Error(init.error.message);

List and call tools. An allowed call returns the upstream result after inspection; a call that needs approval returns a tool error the model can read, with machine-readable details in _meta.gebsecure:

docs/site/snippets/mcp/client.ts
// Only tools that are pinned, unquarantined and allowed for this server are listed.
const tools = await rpc('tools/list');
console.log('tools:', tools.result?.tools?.map((t) => t.name).join(', '));

// Allowed by policy: forwarded upstream, result inspected (DLP + prompt injection) and audited.
const forecast = await rpc('tools/call', { name: 'get_forecast', arguments: { city: 'Lisbon' } });
console.log('get_forecast:', forecast.result?.content?.[0]?.text);

// Needs approval: GebSecure answers with a tool error the model can read, plus machine-readable _meta.
const del = await rpc('tools/call', { name: 'delete_note', arguments: { id: 'note-7' } });
const meta = del.result?._meta?.gebsecure ?? {};
console.log('delete_note:', del.result?.isError ? `blocked (${String(meta.decision)}, approval ${String(meta.approvalId)})` : 'ran');
docs/site/snippets/mcp/client.ts
await fetch(endpoint, { method: 'DELETE', headers: { authorization: `Bearer ${await gs.getAccessToken()}`, 'mcp-session-id': sessionId ?? '' } });
bash
npx tsx --tsconfig docs/site/snippets/tsconfig.json docs/site/snippets/mcp/client.ts
# tools: delete_note, get_forecast
# get_forecast: Sunny in Lisbon, 21°C
# delete_note: blocked (APPROVAL_REQUIRED, approval apr_…)

When a reviewer approves the request, the agent retries the identical call: the gateway finds the approved request for the same snapshot (principal, tool, arguments) and consumes it.

Any MCP client that supports Streamable HTTP with custom headers can connect the same way: point it at {gateway}/v1/mcp/{slug} (one server) or {gateway}/v1/mcp (every server the agent may use, with tools named {slug}__{tool}) and send Authorization: Bearer <token>. An unauthenticated request receives WWW-Authenticate: Bearer resource_metadata="{gateway}/.well-known/oauth-protected-resource".

Next steps#