@neon/skills 3.0.4 → 3.0.6
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 +1 -1
- package/plugin.json +1 -1
- package/skills/neon/SKILL.md +1 -1
- package/skills/neon-auth/references/oauth-server.md +25 -6
- package/skills/neon-functions/SKILL.md +39 -8
- package/skills/neon-functions/references/mastra-studio.md +6 -3
- package/skills/neon-functions/references/mcp.md +180 -58
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.6",
|
|
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
|
@@ -377,7 +377,7 @@ neon deploy --env <file> # apply neon.ts. Pass --env when Function env reads pr
|
|
|
377
377
|
|
|
378
378
|
`<file>` is the gitignored file `neon env pull` already writes (`.env` if that file exists, otherwise `.env.local`). Env pull writes Neon-managed vars only (`DATABASE_URL`, `NEON_AI_GATEWAY_*`, …). Add every key under `functions.*.env` to that file yourself, then pass the same path to `--env`.
|
|
379
379
|
|
|
380
|
-
|
|
380
|
+
Declare each Function secret as `{ value: process.env.X, required: true }` (`@neon/config` 1.13.0 and `neon` 9.2.0 or later; `@neon/env` 2.1.0 or later for `parseEnv`). An unset required value fails `neon deploy` and `neon dev` before anything changes, and never fails an import of `neon.ts`. Use `required: false` for an optional value, or `required: "default-branch"` for one only the default branch's deployment needs; when unset, either is removed from the deployment unless it also sets `onUndefined: "skip"`. Never coerce a missing value to an empty string: that uploads `""` and deletes the live key. An empty assignment in the file (`KEY=`) counts as unset. See the `neon-functions` skill for the full table.
|
|
381
381
|
|
|
382
382
|
Use `neon functions deploy` when you are not applying `neon.ts`: a single function by slug, or a targeted `--env KEY=VALUE` update (that flag is not a file path).
|
|
383
383
|
|
|
@@ -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.
|
|
@@ -147,7 +147,7 @@ neon dev # serves every function in neon.ts with hot reload; injects DATABA
|
|
|
147
147
|
neon deploy --env <file> # preferred full deploy from neon.ts; --env is the file Function env is read from
|
|
148
148
|
```
|
|
149
149
|
|
|
150
|
-
Keep `.env` or `.env.local` up to date with every key under `functions.*.env`. `neon env pull` writes Neon-managed vars only; add Function secrets to that file, then pass it as `--env`. `neon deploy --env <file>` loads that file into `process.env` each time, then uploads
|
|
150
|
+
Keep `.env` or `.env.local` up to date with every key under `functions.*.env`. `neon env pull` writes Neon-managed vars only; add Function secrets to that file, then pass it as `--env`. `neon deploy --env <file>` loads that file into `process.env` each time, then uploads the declared values. Declare each secret as `{ value: process.env.X, required: true }` (see "Your own secrets" below): an unset required value fails `neon deploy` and `neon dev` before anything changes, and never fails an import of `neon.ts`. Never coerce a missing value to `""` (that uploads `""` and deletes the live key); an empty assignment (`KEY=`) counts as unset.
|
|
151
151
|
|
|
152
152
|
To deploy a single function without applying `neon.ts`: `neon functions deploy <slug> --src src/index.ts` (`--src` takes either the entry file or a directory containing `index.ts`, `index.mjs`, or `index.js`). That command's `--env` is `KEY=VALUE` (repeatable), not a file path. Use it for a targeted env update. Retrieve the public URL with `neon functions get <slug>` (the `invocation_url` field, of the form `https://<branch_id>-<slug>.compute.<cell>.us-east-2.aws.neon.tech`). Manage with `neon functions list|get|delete`.
|
|
153
153
|
|
|
@@ -205,18 +205,32 @@ Object storage (`AWS_*`) and AI Gateway (`NEON_AI_GATEWAY_*`) vars are also inje
|
|
|
205
205
|
|
|
206
206
|
`neon env pull` / `neon-env run` / `neon dev` emit `NEON_BRANCH`, `NEON_BRANCH_ID`, `NEON_FUNCTION_HOST_SUFFIX` (and the connection strings) into your local dev environment too, so local runs mirror the deployed runtime.
|
|
207
207
|
|
|
208
|
-
**Your own secrets** are per-deployment. Preferred path: declare them in `neon.ts` and run `neon deploy --env <file>`. `<file>` is the gitignored file env pull already writes (`.env` if that file exists, otherwise `.env.local`). Env pull writes Neon-managed vars only; add Function secrets to that file.
|
|
208
|
+
**Your own secrets** are per-deployment. Preferred path: declare them in `neon.ts` and run `neon deploy --env <file>`. `<file>` is the gitignored file env pull already writes (`.env` if that file exists, otherwise `.env.local`). Env pull writes Neon-managed vars only; add Function secrets to that file. Declare each one with both `value` and `required` (needs `@neon/config` 1.13.0 and `neon` 9.2.0 or later, and `@neon/env` 2.1.0 or later where the function calls `parseEnv`; older `parseEnv` treats every declared key as required):
|
|
209
209
|
|
|
210
210
|
```typescript
|
|
211
211
|
functions: {
|
|
212
212
|
todos: {
|
|
213
213
|
name: "todo api",
|
|
214
214
|
source: "src/index.ts",
|
|
215
|
-
env: {
|
|
215
|
+
env: {
|
|
216
|
+
RESEND_API_KEY: { value: process.env.RESEND_API_KEY, required: true },
|
|
217
|
+
SENTRY_DSN: { value: process.env.SENTRY_DSN, required: "default-branch" },
|
|
218
|
+
LOG_LEVEL: "info",
|
|
219
|
+
},
|
|
216
220
|
},
|
|
217
221
|
}
|
|
218
222
|
```
|
|
219
223
|
|
|
224
|
+
| `required` | Unset deploying the default branch | Unset deploying another branch | Unset in `neon dev` | `parseEnv(config, slug).function` |
|
|
225
|
+
| --- | --- | --- | --- | --- |
|
|
226
|
+
| `true` | fails before any change | fails before any change | fails before any function starts | `string` |
|
|
227
|
+
| `"default-branch"` | fails before any change | removed from the deployment | runs without it | `string \| undefined` |
|
|
228
|
+
| `false` | removed from the deployment | removed from the deployment | runs without it | `string \| undefined` |
|
|
229
|
+
|
|
230
|
+
An undefined or empty value counts as unset; put a fallback in `value` (`process.env.X ?? "1"`). `"default-branch"` is the branch Neon marks as default, not a branch name. Add `onUndefined: "skip"` to a `required: false` or `"default-branch"` variable to keep its deployed value instead of removing it, for a value set with `neon functions deploy --env`. Keys `neon.ts` does not declare are left alone.
|
|
231
|
+
|
|
232
|
+
Prefer a declaration over a string such as `process.env.X!`. A string is validated wherever `neon.ts` is imported, so a function that calls `parseEnv(config, "<slug>")` fails to load when another function's secret is missing from its runtime. A declaration is checked only when a command needs its value.
|
|
233
|
+
|
|
220
234
|
`neon functions deploy --env KEY=VALUE` is the manual path (repeatable; `--env KEY=` deletes a key; unmentioned keys carry over). Use it for a targeted env update, not a full `neon.ts` apply.
|
|
221
235
|
|
|
222
236
|
Load Function secrets into the same file env pull wrote, then `neon deploy --env <file>`. Pull the branch's Neon-managed vars onto disk for local dev with `neon env pull` (`link`/`checkout` do this automatically; pass `--no-env-pull` to skip and use `neon-env run -- <cmd>` for runtime injection). Limits: ≤1,000 vars, ≤64 KiB total, and the `NEON_` prefix is reserved.
|
|
@@ -647,16 +661,33 @@ Trigger routes must not require a user JWT or `X-Secret`; Neon POSTs to the nati
|
|
|
647
661
|
|
|
648
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.
|
|
649
663
|
|
|
650
|
-
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:
|
|
651
665
|
|
|
652
666
|
```typescript
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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);
|
|
657
686
|
});
|
|
658
687
|
```
|
|
659
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
|
+
|
|
660
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`.
|
|
661
692
|
|
|
662
693
|
## Integrations and Observability
|
|
@@ -93,7 +93,7 @@ Two gotchas:
|
|
|
93
93
|
|
|
94
94
|
## 5. Pass the creds via `neon.ts` (third-party env)
|
|
95
95
|
|
|
96
|
-
Neon-injected vars (`DATABASE_URL`, AI Gateway `NEON_AI_GATEWAY_*`) are automatic. Declare only third-party vars under the function's `env`,
|
|
96
|
+
Neon-injected vars (`DATABASE_URL`, AI Gateway `NEON_AI_GATEWAY_*`) are automatic. Declare only third-party vars under the function's `env`, each with `value` and `required`:
|
|
97
97
|
|
|
98
98
|
```typescript
|
|
99
99
|
// neon.ts
|
|
@@ -102,8 +102,11 @@ functions: {
|
|
|
102
102
|
name: "my app",
|
|
103
103
|
source: "src/index.ts",
|
|
104
104
|
env: {
|
|
105
|
-
MASTRA_PROJECT_ID: process.env.MASTRA_PROJECT_ID
|
|
106
|
-
MASTRA_PLATFORM_ACCESS_TOKEN:
|
|
105
|
+
MASTRA_PROJECT_ID: { value: process.env.MASTRA_PROJECT_ID, required: true },
|
|
106
|
+
MASTRA_PLATFORM_ACCESS_TOKEN: {
|
|
107
|
+
value: process.env.MASTRA_PLATFORM_ACCESS_TOKEN,
|
|
108
|
+
required: true,
|
|
109
|
+
},
|
|
107
110
|
},
|
|
108
111
|
},
|
|
109
112
|
}
|
|
@@ -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.
|