@neon/skills 3.0.5 → 3.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "neon-postgres",
|
|
4
|
-
"version": "3.0.
|
|
4
|
+
"version": "3.0.7",
|
|
5
5
|
"description": "Manage your Neon backend with the Neon agent skills and the Neon MCP Server: Lakebase Postgres, Managed Better Auth, Realtime, Object Storage, Functions, the Data API, and AI Gateway",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Neon",
|
package/skills/neon/SKILL.md
CHANGED
|
@@ -86,6 +86,7 @@ New projects are created in AWS regions. Prefer pooled `DATABASE_URL` for applic
|
|
|
86
86
|
| User asked to migrate from Supabase Auth | `neon-auth` (Managed Better Auth; keep `SupabaseAuthAdapter()` call shapes) |
|
|
87
87
|
| Files, uploads, blobs (no existing object store) | Object Storage |
|
|
88
88
|
| HTTP APIs, cron, custom WebSocket or SSE push, long-running agents | Functions querying Postgres |
|
|
89
|
+
| MCP server | `neon-functions`, unless the user asks to deploy it elsewhere |
|
|
89
90
|
| Live queries for realtime, reactive apps and agents; optimistic mutations | `neon-realtime` (`preview.realtime` in `neon.ts`). Not available on Claimable projects until claimed |
|
|
90
91
|
| LLM calls | AI Gateway |
|
|
91
92
|
| Caching hot reads, rate limits | Upstash Redis |
|
|
@@ -130,7 +131,7 @@ The skills below live in the [`neondatabase/agent-skills`](https://github.com/ne
|
|
|
130
131
|
| `neon-postgres` | Working with databases, including connections, schemas, queries, search, branching workflows, egress optimization, autoscaling, performance, and scaling decisions. |
|
|
131
132
|
| `neon-auth` | Identity routing and Managed Better Auth setup (login, users, sessions, trusted domains). Fetch: https://neon.com/docs/ai/skills/neon-auth/SKILL.md |
|
|
132
133
|
| `neon-object-storage` | Storing and serving files (uploads, images, blobs), including branching them with the database. |
|
|
133
|
-
| `neon-functions` | Deploying long-running or streaming serverless functions — APIs, agents, SSE/WebSocket servers, and Function Triggers (cron and object-storage).
|
|
134
|
+
| `neon-functions` | Deploying long-running or streaming serverless functions — APIs, agents, MCP servers, SSE/WebSocket servers, and Function Triggers (cron and object-storage). |
|
|
134
135
|
| `neon-ai-gateway` | Calling an LLM or routing across model providers with one credential, including discovering the branch's servable models at runtime via the OpenAI-compatible `/v1/models` endpoint. |
|
|
135
136
|
| `neon-realtime` | Realtime makes any SQL query live, for realtime, reactive apps and agents: enabling Realtime, sealing queries, React and TanStack DB bindings, SSR, and optimistic mutations. |
|
|
136
137
|
|
|
@@ -520,3 +521,16 @@ If that check fails, inspect the available Neon MCP tools and use `send_feedback
|
|
|
520
521
|
The goal is to improve the user's experience without interrupting or getting in the way of their current work. If submission fails, do not retry. Finish the user's task normally.
|
|
521
522
|
|
|
522
523
|
**Never send secrets or sensitive data.** Remove credentials, tokens, API keys, passwords, personal or customer data, and confidential project details from the report. Send only the issue report described above; do not collect or infer analytics.
|
|
524
|
+
|
|
525
|
+
## FAQ
|
|
526
|
+
|
|
527
|
+
### My Free plan project hit its compute or network transfer limit. How do I get my data out?
|
|
528
|
+
|
|
529
|
+
On the Free plan, running out of CU-hours or public network transfer suspends the compute until the next billing period or until you upgrade. No data is deleted, but nothing can connect, including `pg_dump`: connections fail with SQLSTATE `53000` ("Your account or project has exceeded the quota"). See [What happens if I exceed my Free plan limits?](https://neon.com/docs/introduction/plans.md).
|
|
530
|
+
|
|
531
|
+
There are two ways out:
|
|
532
|
+
|
|
533
|
+
1. **Wait for the reset.** CU-hours and network transfer reset at the start of each monthly billing period.
|
|
534
|
+
2. **Upgrade to Launch, export, and move the data.** Launch has no minimum monthly fee, and invoices under $0.50 are not collected ([Price](https://neon.com/docs/introduction/plans.md#price)). Upgrade the organization that contains the project (**Billing** > **Change plan** in the Neon Console), run `pg_dump` against the now-running compute ([pg_dump and pg_restore](https://neon.com/docs/import/migrate-from-postgres.md)), and restore the dump into a project in a Free organization or anywhere else. A one-time export of a small database typically stays under $0.50; any usage you keep running in the upgraded organization is billed.
|
|
535
|
+
|
|
536
|
+
A project can't be transferred from a Launch organization into a Free one, because the destination plan must be the same tier or higher ([Transfer projects](https://neon.com/docs/manage/orgs-project-transfer.md)), so move the data with a dump and restore. A temporary limit increase from the Neon team takes time to process and rarely lands before the reset; upgrading is faster.
|
|
@@ -97,15 +97,15 @@ The user identity is the token's `sub`. Never trust a user id from tool argument
|
|
|
97
97
|
Verify `iss` (the exact Auth URL of the branch) and `aud` (the exact MCP server URL) as well as the signature. All branches of a project share signing keys, so the signature alone does not identify the branch. `@neon/oauth` 0.3.0 or later (beta) does all three.
|
|
98
98
|
|
|
99
99
|
```bash
|
|
100
|
-
npm install @neon/oauth @modelcontextprotocol/sdk hono
|
|
100
|
+
npm install @neon/oauth @modelcontextprotocol/sdk@^1.30.0 hono
|
|
101
101
|
```
|
|
102
102
|
|
|
103
103
|
On a Neon Function, the default export is a Hono app (see the `neon-functions` skill, [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md)):
|
|
104
104
|
|
|
105
105
|
```typescript
|
|
106
106
|
import { Hono } from "hono";
|
|
107
|
-
import { StreamableHTTPTransport } from "@hono/mcp";
|
|
108
107
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
108
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
109
109
|
import { createMcpAuth } from "@neon/oauth/mcp";
|
|
110
110
|
import { honoMcp, type McpAuthVariables } from "@neon/oauth/mcp/hono";
|
|
111
111
|
|
|
@@ -117,19 +117,38 @@ const mcpAuth = createMcpAuth({
|
|
|
117
117
|
const app = new Hono<McpAuthVariables>();
|
|
118
118
|
app.use(honoMcp(mcpAuth, { path: "/mcp" })); // metadata routes + bearer guard
|
|
119
119
|
|
|
120
|
-
|
|
120
|
+
// Stateless: no standalone SSE stream and no session to delete.
|
|
121
|
+
app.on(["GET", "DELETE"], "/mcp", (c) =>
|
|
122
|
+
c.json(
|
|
123
|
+
{
|
|
124
|
+
jsonrpc: "2.0",
|
|
125
|
+
error: { code: -32000, message: "Method not allowed." },
|
|
126
|
+
id: null,
|
|
127
|
+
},
|
|
128
|
+
405,
|
|
129
|
+
{ Allow: "POST" },
|
|
130
|
+
),
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
app.post("/mcp", async (c) => {
|
|
121
134
|
const userId = c.get("auth").sub; // verified identity; scope every query by it
|
|
122
135
|
const server = new McpServer({ name: "my-mcp", version: "1.0.0" });
|
|
123
136
|
// register tools that close over userId
|
|
124
|
-
const transport = new
|
|
137
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
138
|
+
sessionIdGenerator: undefined,
|
|
139
|
+
});
|
|
125
140
|
await server.connect(transport);
|
|
126
|
-
return transport.handleRequest(c
|
|
141
|
+
return transport.handleRequest(c.req.raw, {
|
|
142
|
+
authInfo: c.get("authInfo"),
|
|
143
|
+
});
|
|
127
144
|
});
|
|
128
145
|
|
|
129
146
|
export default app;
|
|
130
147
|
```
|
|
131
148
|
|
|
132
|
-
-
|
|
149
|
+
- Use the official Web Standard transport on Neon Functions. It matches the runtime's `Request` / `Response` interface directly and, from SDK 1.30.0, sends SSE keep-alives every 15 seconds. `@hono/mcp` sends no keep-alives on POST responses, so a slow tool call can hit a client's 30-second connection timeout on Neon Functions.
|
|
150
|
+
- The official transport enforces the MCP `Accept` headers. Use `@hono/mcp` only as a compatibility fallback for a known client that does not send the required headers. Its wiring is in the `neon-functions` skill, [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md#fallback-for-non-compliant-clients).
|
|
151
|
+
- Stateless: build the server and transport per request. Pass `c.req.raw` and `c.get("authInfo")` to `handleRequest`. Return `405` with `Allow: POST` for GET and DELETE, so a GET does not hold an idle SSE stream open. `honoMcp` still checks the token on those methods.
|
|
133
152
|
- `c.get("auth")` is the verified result (`sub`, `clientId`, `scopes`, `claims`); `c.get("authInfo")` is the MCP SDK `AuthInfo`. Express, Next.js, and `node:http` adapters exist (`@neon/oauth/mcp/express`, `/next`, `/node`).
|
|
134
153
|
- Set `NEON_AUTH_BASE_URL` and `MCP_RESOURCE` through the Function's `env` in `neon.ts`, and deploy with `neon deploy` (or `neon functions deploy <name> --src <file>`).
|
|
135
154
|
- Known gaps: a request with no token gets a challenge with `error="invalid_token"` rather than a bare RFC 6750 challenge, and `/mcp` has no CORS or `OPTIONS` handling, so browser-based MCP clients need CORS added by you.
|
|
@@ -661,16 +661,33 @@ Trigger routes must not require a user JWT or `X-Secret`; Neon POSTs to the nati
|
|
|
661
661
|
|
|
662
662
|
An [MCP](https://modelcontextprotocol.io) server is a natural Functions workload: a long-running HTTP handler that exposes tools to AI clients (Cursor, Claude, ChatGPT, agents), with those tools reading and writing the branch's Postgres right next to the compute. MCP's **streamable HTTP transport** is a plain `POST`/`GET` on a single endpoint (conventionally `/mcp`), so it maps onto a function's `fetch` handler with no `upgrade` method or extra protocol.
|
|
663
663
|
|
|
664
|
-
The simplest host is a Hono app using the official [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk)
|
|
664
|
+
The simplest host is a Hono app using the official [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk) and its `WebStandardStreamableHTTPServerTransport`. It maps directly to Hono's raw Web Standard request and, from SDK 1.30.0, sends SSE keep-alives every 15 seconds. Build a stateless server and transport per request, while keeping the database pool at module scope. A stateless server answers only POST, so return `405` with `Allow: POST` for GET and DELETE rather than holding an idle SSE stream open:
|
|
665
665
|
|
|
666
666
|
```typescript
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
667
|
+
app.on(["GET", "DELETE"], "/mcp", (c) =>
|
|
668
|
+
c.json(
|
|
669
|
+
{
|
|
670
|
+
jsonrpc: "2.0",
|
|
671
|
+
error: { code: -32000, message: "Method not allowed." },
|
|
672
|
+
id: null,
|
|
673
|
+
},
|
|
674
|
+
405,
|
|
675
|
+
{ Allow: "POST" },
|
|
676
|
+
),
|
|
677
|
+
);
|
|
678
|
+
|
|
679
|
+
app.post("/mcp", async (c) => {
|
|
680
|
+
const server = createServer();
|
|
681
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
682
|
+
sessionIdGenerator: undefined,
|
|
683
|
+
});
|
|
684
|
+
await server.connect(transport);
|
|
685
|
+
return transport.handleRequest(c.req.raw);
|
|
671
686
|
});
|
|
672
687
|
```
|
|
673
688
|
|
|
689
|
+
The official transport enforces the MCP `Accept` headers. Use `@hono/mcp` only as a compatibility fallback for a known client that does not send the required headers. It sends no keep-alives on POST responses, so a slow tool call can hit a client's 30-second connection timeout. The fallback wiring is in [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md#fallback-for-non-compliant-clients).
|
|
690
|
+
|
|
674
691
|
Because the function's URL is public, **authenticate before connecting the transport** — Managed Better Auth is the OAuth server for third-party MCP clients (guard the Function with `@neon/oauth`; see the `neon-auth` skill's [oauth-server.md](https://neon.com/docs/ai/skills/neon-auth/references/oauth-server.md)), and a simpler API-key / session-JWT check covers your own callers. Public-consumer edge protection: [references/production-hardening.md](references/production-hardening.md). [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md) has the full pattern — server with Postgres-backed tools via Drizzle, the auth options, and testing with `mcporter` / `add-mcp`.
|
|
675
692
|
|
|
676
693
|
## Integrations and Observability
|
|
@@ -6,7 +6,14 @@ MCP's **streamable HTTP transport** is a plain `POST`/`GET` on a single endpoint
|
|
|
6
6
|
|
|
7
7
|
## The server
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Use the official [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk) for both the server and its Web Standard streamable HTTP transport. Neon Functions and Hono expose Web Standard `Request` and `Response` objects, so no transport adapter is needed. Tools query Postgres through Drizzle on a module-scope `pg` pool, exactly like any other function (see [Connecting to Postgres](../SKILL.md#connecting-to-postgres)).
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @modelcontextprotocol/sdk@^1.30.0 hono zod drizzle-orm pg @neon/functions
|
|
13
|
+
npm install -D @types/pg @types/node
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
SDK 1.30.0 is the first version that sends SSE keep-alives, so pin at least that.
|
|
10
17
|
|
|
11
18
|
```typescript
|
|
12
19
|
// src/index.ts
|
|
@@ -16,7 +23,7 @@ import { Pool } from "pg";
|
|
|
16
23
|
import { eq } from "drizzle-orm";
|
|
17
24
|
import { z } from "zod";
|
|
18
25
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
19
|
-
import {
|
|
26
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
20
27
|
import { attachDatabasePool } from "@neon/functions";
|
|
21
28
|
import { contacts } from "./db/schema";
|
|
22
29
|
|
|
@@ -24,55 +31,77 @@ const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
|
|
|
24
31
|
attachDatabasePool(pool);
|
|
25
32
|
const db = drizzle(pool);
|
|
26
33
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
34
|
+
function createServer() {
|
|
35
|
+
const server = new McpServer({ name: "contacts", version: "1.0.0" });
|
|
36
|
+
|
|
37
|
+
// Each tool: a name, a config (description + a Zod input schema), and a handler
|
|
38
|
+
// that returns MCP content. The Zod shape becomes the tool's JSON schema, which
|
|
39
|
+
// the client uses to call the tool correctly.
|
|
40
|
+
server.registerTool(
|
|
41
|
+
"create_contact",
|
|
42
|
+
{
|
|
43
|
+
title: "Create contact",
|
|
44
|
+
description: "Create a new contact.",
|
|
45
|
+
inputSchema: {
|
|
46
|
+
name: z.string().describe("Full name (required)."),
|
|
47
|
+
email: z.string().optional().describe("Email address."),
|
|
48
|
+
},
|
|
40
49
|
},
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
);
|
|
50
|
+
async ({ name, email }) => {
|
|
51
|
+
const [row] = await db
|
|
52
|
+
.insert(contacts)
|
|
53
|
+
.values({ name, email })
|
|
54
|
+
.returning();
|
|
55
|
+
return { content: [{ type: "text", text: JSON.stringify(row) }] };
|
|
56
|
+
},
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
server.registerTool(
|
|
60
|
+
"delete_contact",
|
|
61
|
+
{
|
|
62
|
+
title: "Delete contact",
|
|
63
|
+
description: "Delete a contact by id.",
|
|
64
|
+
inputSchema: { id: z.number().int().positive() },
|
|
65
|
+
},
|
|
66
|
+
async ({ id }) => {
|
|
67
|
+
const [row] = await db
|
|
68
|
+
.delete(contacts)
|
|
69
|
+
.where(eq(contacts.id, id))
|
|
70
|
+
.returning();
|
|
71
|
+
return {
|
|
72
|
+
content: [
|
|
73
|
+
{ type: "text", text: JSON.stringify(row ?? { error: "not found" }) },
|
|
74
|
+
],
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
);
|
|
47
78
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
{
|
|
51
|
-
title: "Delete contact",
|
|
52
|
-
description: "Delete a contact by id.",
|
|
53
|
-
inputSchema: { id: z.number().int().positive() },
|
|
54
|
-
},
|
|
55
|
-
async ({ id }) => {
|
|
56
|
-
const [row] = await db
|
|
57
|
-
.delete(contacts)
|
|
58
|
-
.where(eq(contacts.id, id))
|
|
59
|
-
.returning();
|
|
60
|
-
return {
|
|
61
|
-
content: [
|
|
62
|
-
{ type: "text", text: JSON.stringify(row ?? { error: "not found" }) },
|
|
63
|
-
],
|
|
64
|
-
};
|
|
65
|
-
},
|
|
66
|
-
);
|
|
79
|
+
return server;
|
|
80
|
+
}
|
|
67
81
|
|
|
68
|
-
// Connect the server to the transport once per isolate, then let the Hono route
|
|
69
|
-
// hand every /mcp request (POST for calls, GET for the stream) to the transport.
|
|
70
|
-
const transport = new StreamableHTTPTransport();
|
|
71
82
|
const app = new Hono();
|
|
72
83
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
84
|
+
// Stateless servers never push on a standalone stream or end a session, so
|
|
85
|
+
// refuse GET and DELETE instead of holding an idle SSE stream open.
|
|
86
|
+
app.on(["GET", "DELETE"], "/mcp", (c) =>
|
|
87
|
+
c.json(
|
|
88
|
+
{
|
|
89
|
+
jsonrpc: "2.0",
|
|
90
|
+
error: { code: -32000, message: "Method not allowed." },
|
|
91
|
+
id: null,
|
|
92
|
+
},
|
|
93
|
+
405,
|
|
94
|
+
{ Allow: "POST" },
|
|
95
|
+
),
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
app.post("/mcp", async (c) => {
|
|
99
|
+
const server = createServer();
|
|
100
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
101
|
+
sessionIdGenerator: undefined,
|
|
102
|
+
});
|
|
103
|
+
await server.connect(transport);
|
|
104
|
+
return transport.handleRequest(c.req.raw);
|
|
76
105
|
});
|
|
77
106
|
|
|
78
107
|
export default app;
|
|
@@ -80,7 +109,11 @@ export default app;
|
|
|
80
109
|
|
|
81
110
|
Key points:
|
|
82
111
|
|
|
83
|
-
- **
|
|
112
|
+
- **Official transport.** Default to `WebStandardStreamableHTTPServerTransport`. It matches the Neon Functions runtime directly and, from `@modelcontextprotocol/sdk` 1.30.0, sends SSE keep-alives every 15 seconds while a tool call runs. `@hono/mcp` sends no keep-alives on POST responses, so a slow tool call can hit a client's 30-second connection timeout.
|
|
113
|
+
- **Strict headers.** The official transport enforces the MCP `Accept` headers. Use `@hono/mcp` only as a compatibility fallback for a known client that does not send the required headers (see [the fallback](#fallback-for-non-compliant-clients)).
|
|
114
|
+
- **Per request.** Build a stateless server and transport for each request. Keep only the `pg` pool and other concurrency-safe resources at module scope (see [runtime limits](../SKILL.md#timeouts-and-runtime-limits)).
|
|
115
|
+
- **POST only.** A stateless server answers each POST on that request's own response, so it has no use for the standalone GET stream or a DELETE that ends a session. Return `405` with an `Allow: POST` header for both, as the SDK's stateless examples do. Otherwise a GET opens an SSE stream that nothing ever writes to, and it stays open until the client leaves or the function times out.
|
|
116
|
+
- **Cleanup.** No `close()` call is needed. The transport closes a POST's stream once the last response is sent, and clears the stream and its keep-alive timer if the client cancels. The per-request server and transport are then garbage collected.
|
|
84
117
|
- **State in Postgres.** Module memory doesn't survive isolate eviction, and several isolates run in parallel — so the source of truth for anything a tool reads or writes belongs in Postgres, not an in-memory structure.
|
|
85
118
|
- **The URL.** After `neon deploy`, the server lives at `https://<branch_id>-<slug>.compute.…neon.tech/mcp`. Point any streamable-HTTP MCP client at that `/mcp` path.
|
|
86
119
|
|
|
@@ -102,12 +135,48 @@ neon neon-auth config oauth-server update --enabled \
|
|
|
102
135
|
--mcp-resource https://<your-function-url>/mcp
|
|
103
136
|
```
|
|
104
137
|
|
|
105
|
-
Your Neon Function is the **resource server**. `honoMcp` verifies the token's signature, issuer, and audience, serves the protected-resource metadata, and answers unauthenticated requests with a `401` challenge. It sets `c.get("auth")`, whose `sub` is the user identity. Scope every tool to it
|
|
138
|
+
Your Neon Function is the **resource server**. `honoMcp` verifies the token's signature, issuer, and audience, serves the protected-resource metadata, and answers unauthenticated requests with a `401` challenge. It sets `c.get("auth")`, whose `sub` is the user identity. Scope every tool to it. This server factory takes the caller's `userId`, and its tools close over it (the example assumes `contacts` has an `ownerId` column).
|
|
139
|
+
|
|
140
|
+
This code replaces the main example's `createServer`, `app`, and routes. Keep its imports, pool, and `db`:
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
npm install @neon/oauth
|
|
144
|
+
```
|
|
106
145
|
|
|
107
146
|
```typescript
|
|
147
|
+
import { and } from "drizzle-orm"; // eq, z, db, and contacts come from the main example
|
|
108
148
|
import { createMcpAuth } from "@neon/oauth/mcp";
|
|
109
149
|
import { honoMcp, type McpAuthVariables } from "@neon/oauth/mcp/hono";
|
|
110
150
|
|
|
151
|
+
function createUserServer(userId: string) {
|
|
152
|
+
const server = new McpServer({ name: "contacts", version: "1.0.0" });
|
|
153
|
+
|
|
154
|
+
// Register create_contact as in the main example, but insert
|
|
155
|
+
// .values({ name, email, ownerId: userId }) so the row belongs to the caller.
|
|
156
|
+
|
|
157
|
+
server.registerTool(
|
|
158
|
+
"delete_contact",
|
|
159
|
+
{
|
|
160
|
+
title: "Delete contact",
|
|
161
|
+
description: "Delete one of your contacts by id.",
|
|
162
|
+
inputSchema: { id: z.number().int().positive() },
|
|
163
|
+
},
|
|
164
|
+
async ({ id }) => {
|
|
165
|
+
const [row] = await db
|
|
166
|
+
.delete(contacts)
|
|
167
|
+
.where(and(eq(contacts.id, id), eq(contacts.ownerId, userId)))
|
|
168
|
+
.returning();
|
|
169
|
+
return {
|
|
170
|
+
content: [
|
|
171
|
+
{ type: "text", text: JSON.stringify(row ?? { error: "not found" }) },
|
|
172
|
+
],
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
return server;
|
|
178
|
+
}
|
|
179
|
+
|
|
111
180
|
const mcpAuth = createMcpAuth({
|
|
112
181
|
baseUrl: process.env.NEON_AUTH_BASE_URL!, // the branch's Auth URL
|
|
113
182
|
resource: process.env.MCP_RESOURCE!, // exactly the --mcp-resource value
|
|
@@ -116,17 +185,34 @@ const mcpAuth = createMcpAuth({
|
|
|
116
185
|
const app = new Hono<McpAuthVariables>();
|
|
117
186
|
app.use(honoMcp(mcpAuth, { path: "/mcp" }));
|
|
118
187
|
|
|
119
|
-
app.
|
|
188
|
+
app.on(["GET", "DELETE"], "/mcp", (c) =>
|
|
189
|
+
c.json(
|
|
190
|
+
{
|
|
191
|
+
jsonrpc: "2.0",
|
|
192
|
+
error: { code: -32000, message: "Method not allowed." },
|
|
193
|
+
id: null,
|
|
194
|
+
},
|
|
195
|
+
405,
|
|
196
|
+
{ Allow: "POST" },
|
|
197
|
+
),
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
app.post("/mcp", async (c) => {
|
|
120
201
|
const userId = c.get("auth").sub;
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
202
|
+
const server = createUserServer(userId);
|
|
203
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
204
|
+
sessionIdGenerator: undefined,
|
|
205
|
+
});
|
|
124
206
|
await server.connect(transport);
|
|
125
|
-
return transport.handleRequest(c
|
|
207
|
+
return transport.handleRequest(c.req.raw, {
|
|
208
|
+
authInfo: c.get("authInfo"),
|
|
209
|
+
});
|
|
126
210
|
});
|
|
211
|
+
|
|
212
|
+
export default app;
|
|
127
213
|
```
|
|
128
214
|
|
|
129
|
-
|
|
215
|
+
Keep the `pg` pool at module scope. Never take the user id from tool arguments. Pass the raw Web Standard request and the verified MCP `AuthInfo` to the transport. Pass `NEON_AUTH_BASE_URL` and `MCP_RESOURCE` via the function's `env` in `neon.ts` (see [Environment variables](../SKILL.md#environment-variables)). `/mcp` has no CORS or `OPTIONS` handling from `honoMcp`, so add it for browser-based clients.
|
|
130
216
|
|
|
131
217
|
### Option 2 — API key or session JWT (simplest)
|
|
132
218
|
|
|
@@ -138,18 +224,54 @@ When the callers are your own agents/services or a personal MCP server, you don'
|
|
|
138
224
|
Either way it's one check at the top of the `/mcp` route — reject anything that doesn't carry a valid key/token before connecting the transport:
|
|
139
225
|
|
|
140
226
|
```typescript
|
|
141
|
-
|
|
227
|
+
// Keep the GET/DELETE 405 route from the main example. Without it, Hono answers
|
|
228
|
+
// GET with 404, which MCP clients report as an error.
|
|
229
|
+
app.post("/mcp", async (c) => {
|
|
142
230
|
const auth = c.req.header("authorization");
|
|
143
231
|
if (!(await isValidApiKey(auth)))
|
|
144
232
|
return c.json({ error: "unauthorized" }, 401);
|
|
145
|
-
|
|
146
|
-
|
|
233
|
+
const server = createServer();
|
|
234
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
235
|
+
sessionIdGenerator: undefined,
|
|
236
|
+
});
|
|
237
|
+
await server.connect(transport);
|
|
238
|
+
return transport.handleRequest(c.req.raw);
|
|
147
239
|
});
|
|
148
240
|
```
|
|
149
241
|
|
|
150
|
-
|
|
151
242
|
This keeps the secret server-side, costs nothing to operate, and is trivial to rotate — a solid default until you need third-party clients to self-authorize, at which point reach for Option 1.
|
|
152
243
|
|
|
244
|
+
## Fallback for non-compliant clients
|
|
245
|
+
|
|
246
|
+
The official transport returns `406` when a POST's `Accept` header does not list both `application/json` and `text/event-stream`. If a client you must support lists only one of them, or sends `*/*` or no `Accept` header, swap in [`@hono/mcp`](https://github.com/honojs/middleware/tree/main/packages/mcp). It accepts any of those by default:
|
|
247
|
+
|
|
248
|
+
```bash
|
|
249
|
+
npm install @hono/mcp
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
Replace only the transport lines inside your existing `/mcp` handler. Keep its auth check and its server factory (`createUserServer(userId)` with OAuth):
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
import { StreamableHTTPTransport } from "@hono/mcp";
|
|
256
|
+
|
|
257
|
+
// Inside app.post("/mcp", ...), after the auth check and the server factory:
|
|
258
|
+
const transport = new StreamableHTTPTransport({
|
|
259
|
+
sessionIdGenerator: undefined,
|
|
260
|
+
// JSON-only clients need a JSON reply instead of an SSE stream.
|
|
261
|
+
enableJsonResponse: !(c.req.header("accept") ?? "").includes(
|
|
262
|
+
"text/event-stream",
|
|
263
|
+
),
|
|
264
|
+
});
|
|
265
|
+
await server.connect(transport);
|
|
266
|
+
return transport.handleRequest(c); // the Hono context, not c.req.raw
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Things to know before you use it:
|
|
270
|
+
|
|
271
|
+
- **No keep-alives on POST.** `@hono/mcp` sends keep-alives only on GET streams, which a stateless server refuses. A tool call that runs longer than the client's connection timeout (often 30 seconds) fails. Use the fallback only for clients whose tool calls finish quickly.
|
|
272
|
+
- **JSON replies.** By default it answers every POST with an SSE stream, which a client that accepts only `application/json` may reject. The `enableJsonResponse` line above returns plain JSON to those clients.
|
|
273
|
+
- **Auth info.** `handleRequest` passes `c.get("auth")` to tools as their auth info. With `@neon/oauth`, that is Neon's verified result, not the MCP SDK's `AuthInfo`. Scope tools through the `userId` you pass to the factory, as in Option 1, rather than through the tool's auth info.
|
|
274
|
+
|
|
153
275
|
## Testing
|
|
154
276
|
|
|
155
277
|
Drive the server with any MCP client. [`mcporter`](https://github.com/instructa/mcporter) is a quick CLI for it — `mcporter list <url>/mcp --schema` lists the tools and `mcporter call "<url>/mcp.<tool>" key=value` invokes one (`--allow-http` for a local `neon dev` URL). To wire it into a client interactively, `npx add-mcp <url>/mcp -a <agent>` writes the client config for you.
|