@neon/skills 0.0.0 → 1.1.2
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/LICENSE +202 -0
- package/README.md +158 -1
- package/mcp.json +9 -0
- package/package.json +52 -2
- package/plugin.json +14 -0
- package/skills/neon/SKILL.md +480 -0
- package/skills/neon/references/claimable-neon.md +121 -0
- package/skills/neon-ai-gateway/SKILL.md +315 -0
- package/skills/neon-functions/SKILL.md +580 -0
- package/skills/neon-functions/references/ai-sdk.md +145 -0
- package/skills/neon-functions/references/mastra-studio.md +127 -0
- package/skills/neon-functions/references/mcp.md +146 -0
- package/skills/neon-functions/references/sentry.md +244 -0
- package/skills/neon-functions/references/sse.md +160 -0
- package/skills/neon-object-storage/SKILL.md +228 -0
- package/skills/neon-postgres/SKILL.md +177 -0
- package/skills/neon-postgres-branches/SKILL.md +292 -0
- package/skills/neon-postgres-egress-optimizer/SKILL.md +266 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# AI SDK agents on Neon Functions
|
|
2
|
+
|
|
3
|
+
A Neon Function is a long-lived Node.js 24 process, which makes it a natural host for a [Vercel AI SDK](https://ai-sdk.dev) agent: the handler keeps streaming for the life of the request (15-minute budget, see [Timeouts](../SKILL.md#timeouts-and-runtime-limits)), so multi-step tool loops and image/video generation don't get cut off the way they do on lambda-style serverless. Point the model at the **Neon AI Gateway** (see the `neon-ai-gateway` skill) and there are no extra provider keys to manage — one Neon credential reaches the whole catalog.
|
|
4
|
+
|
|
5
|
+
The AI SDK is the **recommended** way to build agents on Functions from TypeScript: one set of primitives (`streamText`, `generateText`, tool calling, structured output) over every catalog model. For a memory- and workflow-heavy agent with built-in tracing, use Mastra instead (see [references/mastra-studio.md](mastra-studio.md)); both point at the same gateway.
|
|
6
|
+
|
|
7
|
+
The pattern below is a complete agent: it streams chat and, when asked, generates an image, uploads it to Object Storage, and indexes it in Postgres.
|
|
8
|
+
|
|
9
|
+
## 1. Declare the gateway and the function
|
|
10
|
+
|
|
11
|
+
The agent needs the AI Gateway (and, for the image example, an Object Storage bucket). Declare both in `neon.ts` alongside the function — `neon deploy` provisions them and injects the credentials at runtime (see the `neon-ai-gateway` and `neon-object-storage` skills):
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
// neon.ts
|
|
15
|
+
import { defineConfig } from "@neon/config/v1";
|
|
16
|
+
|
|
17
|
+
export default defineConfig({
|
|
18
|
+
preview: {
|
|
19
|
+
aiGateway: true,
|
|
20
|
+
buckets: { images: {} },
|
|
21
|
+
functions: {
|
|
22
|
+
agent: { name: "ai agent", source: "src/index.ts" },
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## 2. The handler: stream a tool-calling agent
|
|
29
|
+
|
|
30
|
+
The function's default export is a web-standard `{ fetch }` handler. The `@neon/ai-sdk-provider` reads the injected gateway credentials automatically, so `neon("<model>")` is all the model config you need — it routes each model to the right dialect (Anthropic → Messages, OpenAI/Codex → Responses, everything else → MLflow). Return `result.toUIMessageStreamResponse()` so the AI SDK's `useChat` hooks can consume the stream:
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
// src/index.ts
|
|
34
|
+
import { neon } from "@neon/ai-sdk-provider";
|
|
35
|
+
import { attachDatabasePool } from "@neon/functions";
|
|
36
|
+
import { streamText, tool, stepCountIs, type ModelMessage } from "ai";
|
|
37
|
+
import { z } from "zod";
|
|
38
|
+
import { drizzle } from "drizzle-orm/node-postgres";
|
|
39
|
+
import { Pool } from "pg";
|
|
40
|
+
import { todos } from "./db/schema";
|
|
41
|
+
|
|
42
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
|
|
43
|
+
attachDatabasePool(pool);
|
|
44
|
+
const db = drizzle(pool);
|
|
45
|
+
|
|
46
|
+
export default {
|
|
47
|
+
async fetch(request: Request) {
|
|
48
|
+
if (request.method !== "POST") {
|
|
49
|
+
return new Response("POST chat messages here", { status: 405 });
|
|
50
|
+
}
|
|
51
|
+
const { messages } = (await request.json()) as { messages: ModelMessage[] };
|
|
52
|
+
|
|
53
|
+
const result = streamText({
|
|
54
|
+
model: neon("claude-sonnet-4-6"), // swap to gpt-5-mini, gemini-3-flash, …
|
|
55
|
+
system: "You are a concise assistant with access to the user's todos.",
|
|
56
|
+
messages,
|
|
57
|
+
tools: {
|
|
58
|
+
countOpenTodos: tool({
|
|
59
|
+
description: "Count the user's open todos.",
|
|
60
|
+
inputSchema: z.object({}),
|
|
61
|
+
execute: async () => ({ open: await db.$count(todos) }),
|
|
62
|
+
}),
|
|
63
|
+
},
|
|
64
|
+
// Let the model call tools and then summarize, instead of stopping after
|
|
65
|
+
// the first tool call. The loop runs in-process — no host timeout.
|
|
66
|
+
stopWhen: stepCountIs(5),
|
|
67
|
+
onError({ error }) {
|
|
68
|
+
console.error("[streamText] error:", error);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
return result.toUIMessageStreamResponse({
|
|
73
|
+
onError: (error) =>
|
|
74
|
+
error instanceof Error ? error.message : String(error),
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`tool({ inputSchema, execute })` is the AI SDK v5+ shape (the parameter is `inputSchema`, not the old `parameters`). The tool's `execute` runs **inside the function**, right next to Postgres — no extra network hop.
|
|
81
|
+
|
|
82
|
+
## 3. Generate images and persist them
|
|
83
|
+
|
|
84
|
+
The gateway exposes the OpenAI Responses **`image_generation`** built-in tool (GPT-5 models only; the image comes back inline as base64). Persist generated assets to Object Storage and index them in Postgres so they branch together — the **recommended** storage client is the Files SDK `neon` adapter (see the `neon-object-storage` skill):
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
import { neon } from "@neon/ai-sdk-provider";
|
|
88
|
+
import { streamText } from "ai";
|
|
89
|
+
import { Files } from "files-sdk";
|
|
90
|
+
import { neon as neonFiles } from "files-sdk/neon";
|
|
91
|
+
import { randomUUID } from "node:crypto";
|
|
92
|
+
|
|
93
|
+
const files = new Files({ adapter: neonFiles({ bucket: "images" }) });
|
|
94
|
+
|
|
95
|
+
const result = streamText({
|
|
96
|
+
model: neon("gpt-5-mini"),
|
|
97
|
+
system:
|
|
98
|
+
"Use image_generation when the user asks for a picture, then describe it.",
|
|
99
|
+
messages,
|
|
100
|
+
tools: {
|
|
101
|
+
image_generation: neon.tools.imageGeneration({
|
|
102
|
+
outputFormat: "jpeg",
|
|
103
|
+
quality: "low", // the gateway caps a response near 640 KB — keep images small
|
|
104
|
+
size: "1024x1024",
|
|
105
|
+
}),
|
|
106
|
+
},
|
|
107
|
+
async onStepFinish({ toolResults }) {
|
|
108
|
+
for (const tr of toolResults) {
|
|
109
|
+
if (tr.toolName !== "image_generation") continue;
|
|
110
|
+
const base64 = imageResultBase64(tr.output);
|
|
111
|
+
if (!base64) continue;
|
|
112
|
+
const key = `generated/${randomUUID()}.jpg`;
|
|
113
|
+
await files.upload(key, Buffer.from(base64, "base64"), {
|
|
114
|
+
contentType: "image/jpeg",
|
|
115
|
+
});
|
|
116
|
+
// …insert a row keyed by `key` into Postgres; serve later via files.url(key)
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Keep generated images small: the gateway caps a single response near 640 KB and has an upstream timeout, so request a compressed JPEG rather than a full-size PNG.
|
|
123
|
+
|
|
124
|
+
## 4. Call it directly from the client (don't proxy the stream)
|
|
125
|
+
|
|
126
|
+
So the long stream isn't cut off by your web host's serverless limits, have the **browser call the function directly** and authenticate at the top of the handler — see [Functions as an agent backend](../SKILL.md#functions-as-an-agent-backend-nextjs-and-similar-frameworks) for the JWT-verify + CORS pattern and the AI SDK `DefaultChatTransport` wiring.
|
|
127
|
+
|
|
128
|
+
## 5. Run and deploy
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
neon dev # injects DATABASE_URL + the gateway/storage creds; hot reload
|
|
132
|
+
neon deploy # provisions the gateway + bucket and deploys the function
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
curl -N -X POST "$(neon functions get agent -o json | jq -r .invocation_url)" \
|
|
137
|
+
-H "content-type: application/json" \
|
|
138
|
+
-d '{"messages":[{"role":"user","content":"How many open todos do I have?"}]}'
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Further reading
|
|
142
|
+
|
|
143
|
+
- Neon AI Gateway dialects, models, and the `@neon/ai-sdk-provider`: the `neon-ai-gateway` skill
|
|
144
|
+
- Storing generated assets that branch with the database: the `neon-object-storage` skill
|
|
145
|
+
- AI SDK agents/tools: https://ai-sdk.dev/docs/foundations/agents
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# Mastra agents with Mastra Studio observability
|
|
2
|
+
|
|
3
|
+
A Neon Function is a long-lived Node.js 24 process, which makes it a natural host for a [Mastra](https://mastra.ai) agent: the agent keeps running for the life of the request, and you point its model at the Neon AI Gateway so there are no extra provider keys. You can keep **running the agent on Neon Functions** while shipping its traces to a **Mastra Studio (Mastra Cloud) project** for observability — the agent runs on Neon, the traces are viewable in Mastra.
|
|
4
|
+
|
|
5
|
+
The shape mirrors any other Node integration (see [sentry.md](sentry.md)): instantiate at module load, gate on env vars so local dev and unconfigured branches stay a no-op, and pass secrets at deploy time via `neon.ts`. `@mastra/core` and `@mastra/observability` bundle cleanly through `neon deploy`'s esbuild with no extra config.
|
|
6
|
+
|
|
7
|
+
## 1. Define the agent against the Neon AI Gateway
|
|
8
|
+
|
|
9
|
+
With `@mastra/core` 1.47+, use a `neon/<model>` magic string — Mastra reads `NEON_AI_GATEWAY_BASE_URL` and `NEON_AI_GATEWAY_TOKEN` from the environment (injected by `neon deploy` / `neon env pull` when `preview.aiGateway` is enabled in `neon.ts`). No manual `url`/`apiKey` or MLflow dialect swap is needed; Mastra routes each model to the correct gateway endpoint.
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
// src/mastra/agents/pricing.ts
|
|
13
|
+
import { Agent } from "@mastra/core/agent";
|
|
14
|
+
|
|
15
|
+
export const pricingAgent = new Agent({
|
|
16
|
+
id: "pricing-analyst",
|
|
17
|
+
name: "pricing-analyst",
|
|
18
|
+
instructions: "You are a meticulous pricing analyst. …",
|
|
19
|
+
model: "neon/gpt-5-mini",
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## 2. Wire observability to Mastra Studio
|
|
24
|
+
|
|
25
|
+
The `MastraPlatformExporter` (from `@mastra/observability`) sends traces to a Mastra Studio project. It reads `MASTRA_PLATFORM_ACCESS_TOKEN` and `MASTRA_PROJECT_ID` from the environment.
|
|
26
|
+
|
|
27
|
+
Gotcha: `Observability` requires **at least one exporter** — passing an empty `exporters` array throws `OBSERVABILITY_INVALID_INSTANCE_CONFIG`. So omit the `observability` option entirely until the platform creds are present, keeping the app runnable before the Mastra project exists (and in local dev).
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
// src/mastra/index.ts
|
|
31
|
+
import { Mastra } from "@mastra/core/mastra";
|
|
32
|
+
import { Observability, MastraPlatformExporter } from "@mastra/observability";
|
|
33
|
+
import { pricingAgent } from "./agents/pricing";
|
|
34
|
+
|
|
35
|
+
const platformReady = Boolean(
|
|
36
|
+
process.env.MASTRA_PLATFORM_ACCESS_TOKEN && process.env.MASTRA_PROJECT_ID,
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
const observability = platformReady
|
|
40
|
+
? new Observability({
|
|
41
|
+
configs: {
|
|
42
|
+
default: { serviceName: "my-app", exporters: [new MastraPlatformExporter()] },
|
|
43
|
+
},
|
|
44
|
+
})
|
|
45
|
+
: undefined;
|
|
46
|
+
|
|
47
|
+
export const mastra = new Mastra({
|
|
48
|
+
agents: { pricingAgent },
|
|
49
|
+
...(observability ? { observability } : {}),
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Agents must be **registered on the `Mastra` instance** (the `agents` map) for their `.generate()` / `.stream()` calls to be traced. Call them via `mastra.getAgent("pricingAgent")`.
|
|
54
|
+
|
|
55
|
+
## 3. Structured output through the gateway
|
|
56
|
+
|
|
57
|
+
The gateway does not enforce **native** structured output, so a bare `structuredOutput: { schema }` can come back missing fields (e.g. a nested `meta` object), failing Zod validation. Set `jsonPromptInjection: true` so Mastra injects the schema into the prompt and the model returns the full shape:
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
const agent = mastra.getAgent("pricingAgent");
|
|
61
|
+
const result = await agent.generate(prompt, {
|
|
62
|
+
structuredOutput: { schema: myZodSchema, jsonPromptInjection: true },
|
|
63
|
+
abortSignal: AbortSignal.timeout(70_000), // bound each attempt; the gateway has an upstream timeout
|
|
64
|
+
});
|
|
65
|
+
const data = result.object; // validated against myZodSchema
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
For resilience, register a second agent on a different model (e.g. `neon/claude-haiku-4-5`) and fall back to it if the primary attempt throws — both models are reachable on the gateway via the same env vars.
|
|
69
|
+
|
|
70
|
+
## 4. Create the Mastra project + token with the CLI
|
|
71
|
+
|
|
72
|
+
Install the Mastra CLI (`npm i -g mastra`) and authenticate. Project/token creation needs a **live login session**:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
mastra auth login # opens a browser; required before the steps below
|
|
76
|
+
mastra auth whoami # shows your user + org id (org_…)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
- **Access token (non-interactive):** `mastra auth tokens create <name>` prints a one-time secret (`sk_…`). This is your `MASTRA_PLATFORM_ACCESS_TOKEN`.
|
|
80
|
+
- **Project:** the interactive `mastra studio projects create` TUI is hard to script. Instead, register the project as part of a Studio deploy, which is non-interactive with `-y` and writes the project id to `.mastra-project.json`:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
mastra studio deploy --org org_xxx --project my-app -y
|
|
84
|
+
# → .mastra-project.json: { "projectId": "…", "projectName": "my-app", "organizationId": "org_…" }
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Use that `projectId` as `MASTRA_PROJECT_ID`.
|
|
88
|
+
|
|
89
|
+
Two gotchas:
|
|
90
|
+
|
|
91
|
+
- **Don't set `MASTRA_API_TOKEN` in the env for project/deploy commands** — it makes the CLI report `No organizations found`. Rely on the interactive login session instead.
|
|
92
|
+
- If you keep multiple env files (e.g. `.env.deploy` and `.env.local`), `studio deploy` errors with `Multiple env files found`; pass `--env-file <file>` to disambiguate.
|
|
93
|
+
|
|
94
|
+
## 5. Pass the creds via `neon.ts` (third-party env)
|
|
95
|
+
|
|
96
|
+
Neon-injected vars (`DATABASE_URL`, AI Gateway `NEON_AI_GATEWAY_*`) are automatic. Declare only third-party vars under the function's `env`, resolved from `process.env` at deploy time:
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
// neon.ts
|
|
100
|
+
functions: {
|
|
101
|
+
myapp: {
|
|
102
|
+
name: "my app",
|
|
103
|
+
source: "src/index.ts",
|
|
104
|
+
env: {
|
|
105
|
+
MASTRA_PROJECT_ID: process.env.MASTRA_PROJECT_ID ?? "",
|
|
106
|
+
MASTRA_PLATFORM_ACCESS_TOKEN: process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? "",
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Load the values from a git-ignored file at deploy time:
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
neon deploy --env .env.deploy
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## 6. Verify
|
|
119
|
+
|
|
120
|
+
Send a request that exercises the agent, then open the Mastra Studio project's **Observability / Traces** view — you'll see the agent run (model calls, latency, token usage) under the `serviceName` you configured. Only `SPAN_ENDED` events are exported, buffered and flushed periodically, so a trace appears a few seconds after the agent run completes.
|
|
121
|
+
|
|
122
|
+
## Further reading
|
|
123
|
+
|
|
124
|
+
- https://mastra.ai/docs/observability/tracing/exporters/cloud
|
|
125
|
+
- https://mastra.ai/reference/observability/tracing/exporters/mastra-platform-exporter
|
|
126
|
+
- https://mastra.ai/docs/agents/structured-output
|
|
127
|
+
- Neon AI Gateway dialects: the `neon-ai-gateway` skill
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# MCP servers on Neon Functions
|
|
2
|
+
|
|
3
|
+
A [Model Context Protocol](https://modelcontextprotocol.io) server is a textbook Neon Functions workload: it's a long-running HTTP handler that an AI client (Cursor, Claude, ChatGPT, an agent) calls to discover and invoke tools, and those tools usually read and write a database. Running it as a Neon Function puts the MCP server's compute next to its Postgres data, gives it a public HTTPS URL, and lets it branch with the rest of your backend — each branch gets its own MCP server against its own isolated data.
|
|
4
|
+
|
|
5
|
+
MCP's **streamable HTTP transport** is a plain `POST`/`GET` on a single endpoint (conventionally `/mcp`), so it maps directly onto a function's web-standard `fetch` handler — no `upgrade` method or extra protocol like [WebSockets](../SKILL.md#websocket-servers) needed. A Hono app is the simplest host.
|
|
6
|
+
|
|
7
|
+
## The server
|
|
8
|
+
|
|
9
|
+
Two packages do the work: the official [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk) (defines the server and its tools) and [`@hono/mcp`](https://github.com/honojs/middleware/tree/main/packages/mcp) (bridges MCP's streamable HTTP transport to a Hono route). 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
|
+
```typescript
|
|
12
|
+
// src/index.ts
|
|
13
|
+
import { Hono } from "hono";
|
|
14
|
+
import { drizzle } from "drizzle-orm/node-postgres";
|
|
15
|
+
import { Pool } from "pg";
|
|
16
|
+
import { eq } from "drizzle-orm";
|
|
17
|
+
import { z } from "zod";
|
|
18
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
19
|
+
import { StreamableHTTPTransport } from "@hono/mcp";
|
|
20
|
+
import { attachDatabasePool } from "@neon/functions";
|
|
21
|
+
import { contacts } from "./db/schema";
|
|
22
|
+
|
|
23
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
|
|
24
|
+
attachDatabasePool(pool);
|
|
25
|
+
const db = drizzle(pool);
|
|
26
|
+
|
|
27
|
+
const mcpServer = new McpServer({ name: "contacts", version: "1.0.0" });
|
|
28
|
+
|
|
29
|
+
// Each tool: a name, a config (description + a Zod input schema), and a handler
|
|
30
|
+
// that returns MCP content. The Zod shape becomes the tool's JSON schema, which
|
|
31
|
+
// the client uses to call the tool correctly.
|
|
32
|
+
mcpServer.registerTool(
|
|
33
|
+
"create_contact",
|
|
34
|
+
{
|
|
35
|
+
title: "Create contact",
|
|
36
|
+
description: "Create a new contact.",
|
|
37
|
+
inputSchema: {
|
|
38
|
+
name: z.string().describe("Full name (required)."),
|
|
39
|
+
email: z.string().optional().describe("Email address."),
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
async ({ name, email }) => {
|
|
43
|
+
const [row] = await db.insert(contacts).values({ name, email }).returning();
|
|
44
|
+
return { content: [{ type: "text", text: JSON.stringify(row) }] };
|
|
45
|
+
},
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
mcpServer.registerTool(
|
|
49
|
+
"delete_contact",
|
|
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
|
+
);
|
|
67
|
+
|
|
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
|
+
const app = new Hono();
|
|
72
|
+
|
|
73
|
+
app.all("/mcp", async (c) => {
|
|
74
|
+
if (!mcpServer.isConnected()) await mcpServer.connect(transport);
|
|
75
|
+
return transport.handleRequest(c);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
export default app;
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Key points:
|
|
82
|
+
|
|
83
|
+
- **Module scope.** Build the `McpServer`, register its tools, create the `StreamableHTTPTransport`, and open the `pg` pool once at module load — they're reused across every request the isolate serves (see [runtime limits](../SKILL.md#timeouts-and-runtime-limits)). Connect the transport lazily with the `isConnected()` guard so it happens once.
|
|
84
|
+
- **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
|
+
- **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
|
+
|
|
87
|
+
## Authenticating the server
|
|
88
|
+
|
|
89
|
+
> [!WARNING]
|
|
90
|
+
> A Neon Function has a **public HTTPS URL — anyone can reach it.** An unauthenticated MCP server hands every caller your tools (and the database behind them). Authenticate at the top of the handler before touching the transport, exactly as for [any client-facing function](../SKILL.md#functions-as-an-agent-backend-nextjs-and-similar-frameworks).
|
|
91
|
+
|
|
92
|
+
[Better Auth](https://better-auth.com) (self-hostable, runs alongside your app) is a good fit, and it covers both common shapes. **Better Auth is evolving quickly** — the MCP plugin is moving out of `better-auth/plugins` into its own `@better-auth/mcp` package (built on the OAuth Provider plugin), which renames `withMcpAuth` → `requireMcpAuth` and `createMcpAuthClient` → `createMcpResourceClient`. Verify the current package and import paths against the [Better Auth MCP docs](https://better-auth.com/docs/plugins/mcp) before wiring it up.
|
|
93
|
+
|
|
94
|
+
### Option 1 — OAuth via the Better Auth MCP plugin (best for third-party clients)
|
|
95
|
+
|
|
96
|
+
The [MCP plugin](https://better-auth.com/docs/plugins/mcp) makes your **Better Auth app the OAuth authorization server** for MCP, implementing the MCP authorization spec end to end: discovery (`/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`), dynamic client registration, and the consent/token flow. MCP clients that support OAuth (Cursor, Claude, ChatGPT) then sign the user in and obtain a token with no API key to copy around.
|
|
97
|
+
|
|
98
|
+
Your Neon Function is the **resource server** — a separate service from the Better Auth app, so it doesn't share a process. Use Better Auth's **remote MCP client** to validate the incoming Bearer token against the auth server's published JWKS, and serve the protected-resource metadata so clients can discover where to authenticate:
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
// src/index.ts (sketch) — verify the bearer token against your remote Better Auth server.
|
|
102
|
+
// Import path/name depend on your Better Auth version (createMcpAuthClient in better-auth/plugins/mcp/client,
|
|
103
|
+
// or createMcpResourceClient in @better-auth/mcp/client) — check the docs.
|
|
104
|
+
import { createMcpAuthClient } from "better-auth/plugins/mcp/client";
|
|
105
|
+
|
|
106
|
+
const mcpAuth = createMcpAuthClient({ authURL: process.env.AUTH_URL }); // your Better Auth base URL
|
|
107
|
+
|
|
108
|
+
app.all("/mcp", async (c) => {
|
|
109
|
+
const session = await mcpAuth.verify?.(c.req.raw); // verifies the Bearer token via the remote JWKS
|
|
110
|
+
if (!session) {
|
|
111
|
+
// Tell the client where to authenticate (RFC 9728 / MCP spec).
|
|
112
|
+
return c.json({ error: "unauthorized" }, 401, {
|
|
113
|
+
"WWW-Authenticate": `Bearer resource_metadata="${process.env.AUTH_URL}/.well-known/oauth-protected-resource"`,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
if (!mcpServer.isConnected()) await mcpServer.connect(transport);
|
|
117
|
+
return transport.handleRequest(c); // scope tools to session.userId
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Pass `AUTH_URL` (and any signing/JWKS config) to the function via its `env` in `neon.ts` (see [Environment variables](../SKILL.md#environment-variables)). Because the function only verifies tokens against the remote server, the Better Auth instance can live anywhere — typically your Next.js / app host on Vercel.
|
|
122
|
+
|
|
123
|
+
### Option 2 — API key or session JWT via self-hosted Better Auth (simplest)
|
|
124
|
+
|
|
125
|
+
When the callers are your own agents/services or a personal MCP server, you don't need the full OAuth dance. Run Better Auth self-hosted and either:
|
|
126
|
+
|
|
127
|
+
- **API keys** — enable Better Auth's [API Key plugin](https://better-auth.com/docs/plugins/api-key), issue a key, and have the function verify the `Authorization: Bearer <key>` (or an `x-api-key` header) on every request; or
|
|
128
|
+
- **Session JWT** — mint a short-lived JWT with Better Auth's `jwt` plugin and verify it in the function against the app's JWKS, the same `jose` pattern used for the [agent backend](../SKILL.md#functions-as-an-agent-backend-nextjs-and-similar-frameworks).
|
|
129
|
+
|
|
130
|
+
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:
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
app.all("/mcp", async (c) => {
|
|
134
|
+
const auth = c.req.header("authorization");
|
|
135
|
+
if (!(await isValidApiKey(auth)))
|
|
136
|
+
return c.json({ error: "unauthorized" }, 401);
|
|
137
|
+
if (!mcpServer.isConnected()) await mcpServer.connect(transport);
|
|
138
|
+
return transport.handleRequest(c);
|
|
139
|
+
});
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
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.
|
|
143
|
+
|
|
144
|
+
## Testing
|
|
145
|
+
|
|
146
|
+
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.
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
# Sentry error monitoring on Neon Functions
|
|
2
|
+
|
|
3
|
+
A Neon Function is a **long-lived Node.js 24 process running a web-standard request/response handler** — not an edge worker or a short-lived lambda. That means any integration SDK that works in an ordinary Node process works here unchanged: you initialize it once at module load, before your handler starts serving requests, and it stays instrumented for the life of the isolate.
|
|
4
|
+
|
|
5
|
+
This reference walks through wiring up Sentry for errors, logs, and traces — including AI-agent tracing, since agents are the workload Functions are built for. The same shape (init module imported first, gated on an env var, secret passed at deploy time) applies to other Node SDKs — see [Other Node integrations](#other-node-integrations) at the end.
|
|
6
|
+
|
|
7
|
+
## Sentry (errors, logs, and traces)
|
|
8
|
+
|
|
9
|
+
Because the runtime is a normal Node process, use the Node SDK `@sentry/node` — not an edge/serverless wrapper. **Use `@sentry/node` ≥10.67.0**: older versions fail to register their tracer against the OpenTelemetry API global the runtime pre-creates, and every span is silently non-recording while errors and logs keep working. The SDK bundles cleanly through `neon deploy`'s esbuild with no extra build config.
|
|
10
|
+
|
|
11
|
+
Sentry has distinct signals, and picking the right one is the main instrumentation decision:
|
|
12
|
+
|
|
13
|
+
1. **Errors** — unhandled route errors and failures your code can't recover from. Each becomes a grouped, alertable _issue_.
|
|
14
|
+
2. **Logs** — recoverable failures and narrative events (a model attempt failed and the agent moved on, a retry, a fallback). Structured, searchable, linked to the trace — and they don't pollute the issue stream.
|
|
15
|
+
3. **Traces** — the request's span tree: the incoming request, outbound fetches, and (for agents) the full model/tool call hierarchy with token usage.
|
|
16
|
+
|
|
17
|
+
All three carry the same trace ID, so from an error you can pivot to the logs and spans of the same request.
|
|
18
|
+
|
|
19
|
+
### Environment variables
|
|
20
|
+
|
|
21
|
+
| Variable | Purpose |
|
|
22
|
+
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
23
|
+
| `SENTRY_DSN` | Project DSN; keep it configurable through the deployment environment. |
|
|
24
|
+
| `SENTRY_RELEASE` | Optional release identifier such as a commit SHA — unlocks regression detection. |
|
|
25
|
+
| `SENTRY_TRACES_SAMPLE_RATE` | Trace sample rate, default `1`. Agents are low-throughput and every trace is interesting; lower it for high-volume plain HTTP. |
|
|
26
|
+
| `PRODUCTION_BRANCH` | Your default branch's name, so it reports as environment `production` (see below). |
|
|
27
|
+
|
|
28
|
+
### 1. Initialize before anything else
|
|
29
|
+
|
|
30
|
+
Put `Sentry.init` in its own module and import it as the very first import of your entry file, so the process is instrumented before any other code (your handler, the DB pool, the agent) loads.
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
// src/instrument.ts
|
|
34
|
+
import * as Sentry from "@sentry/node";
|
|
35
|
+
|
|
36
|
+
Sentry.init({
|
|
37
|
+
dsn: process.env.SENTRY_DSN,
|
|
38
|
+
enabled: Boolean(process.env.SENTRY_DSN),
|
|
39
|
+
enableLogs: true,
|
|
40
|
+
tracesSampleRate: Number(process.env.SENTRY_TRACES_SAMPLE_RATE ?? 1),
|
|
41
|
+
traceLifecycle: "stream",
|
|
42
|
+
streamGenAiSpans: true,
|
|
43
|
+
integrations: [
|
|
44
|
+
Sentry.vercelAIIntegration({ force: true }),
|
|
45
|
+
Sentry.httpIntegration({ disableIncomingRequestSpans: true }),
|
|
46
|
+
],
|
|
47
|
+
release: process.env.SENTRY_RELEASE,
|
|
48
|
+
environment:
|
|
49
|
+
process.env.NEON_BRANCH &&
|
|
50
|
+
process.env.NEON_BRANCH !== process.env.PRODUCTION_BRANCH
|
|
51
|
+
? process.env.NEON_BRANCH
|
|
52
|
+
: "production",
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
process.on("SIGTERM", () => void Sentry.flush(2000));
|
|
56
|
+
process.on("SIGINT", () => void Sentry.flush(2000));
|
|
57
|
+
|
|
58
|
+
export { Sentry };
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
// src/index.ts
|
|
63
|
+
import "./instrument"; // MUST be the first import, before the framework/agent
|
|
64
|
+
import { Sentry } from "./instrument";
|
|
65
|
+
import { attachDatabasePool } from "@neon/functions";
|
|
66
|
+
import { Hono } from "hono";
|
|
67
|
+
import { Pool } from "pg";
|
|
68
|
+
|
|
69
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
|
|
70
|
+
attachDatabasePool(pool, {
|
|
71
|
+
onUnexpectedError: (err) => Sentry.captureException(err),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// ... rest of the function
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- **Gate `enabled` on the DSN.** Local dev (`neon dev`) and any branch where you haven't configured the secret then become a no-op — no init, no noise — without changing code.
|
|
78
|
+
- **`enableLogs: true`** — the `Sentry.logger.*` API is off by default.
|
|
79
|
+
- **`traceLifecycle: "stream"`** — sends each span as it finishes instead of holding the whole tree until the request ends, so spans that complete after the response (streaming agent calls) aren't lost. `streamGenAiSpans: true` is the default on current SDKs (sends gen_ai spans as standalone items so large prompts aren't truncated); set it to `false` on self-hosted Sentry.
|
|
80
|
+
- **The two integrations:** `vercelAIIntegration({ force: true })` because `neon deploy` bundles your code, which defeats the integration's module detection; `httpIntegration({ disableIncomingRequestSpans: true })` because the request root span comes from the middleware in step 3 (the runtime's internal server would otherwise add a duplicate with an unhelpful name).
|
|
81
|
+
- **Environment:** `NEON_BRANCH` is injected on every branch — including the default — and holds the branch **name** (e.g. `main`, `preview/add-auth`). Because it's always present, don't use it as a boolean flag; compare it against your default branch's name (passed in as `PRODUCTION_BRANCH`) so the default branch reads as `production` and other branches tag by name. Pass `SENTRY_ENVIRONMENT` explicitly per deploy to override.
|
|
82
|
+
- **Flush on shutdown:** the runtime sends `SIGTERM`/`SIGINT` before evicting an idle isolate; Sentry buffers logs and batches spans, so flush or the tail gets dropped.
|
|
83
|
+
- **Idle `pg` pool errors:** call `attachDatabasePool(pool)` (or pass `onUnexpectedError: (err) => Sentry.captureException(err)` on the first call). Don't `pool.end()` on SIGINT — Neon's pooler reclaims those connections. See [Connecting to Postgres](../SKILL.md#connecting-to-postgres).
|
|
84
|
+
|
|
85
|
+
### 2. Provide the DSN as a deploy-time secret
|
|
86
|
+
|
|
87
|
+
The DSN is your own secret, so set it per-deployment (see [Environment Variables](../SKILL.md#environment-variables)). Either pass it on deploy:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
neon functions deploy <slug> --src src/index.ts \
|
|
91
|
+
--env "SENTRY_DSN=https://…@…ingest.us.sentry.io/…" \
|
|
92
|
+
--env "SENTRY_RELEASE=$(git rev-parse --short HEAD)" \
|
|
93
|
+
--env "SENTRY_TRACES_SAMPLE_RATE=1"
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
or declare it under the function's `env` in `neon.ts` (read from `process.env` to avoid hardcoding). Deploy env vars **persist and accumulate across deployments** — omitting `--env` on a later deploy does not clear a variable set earlier.
|
|
97
|
+
|
|
98
|
+
### 3. Create the request span and catch route errors
|
|
99
|
+
|
|
100
|
+
The runtime invokes your handler through its own ingress rather than a plain `node:http` server, so give each request an isolation scope and a root span yourself — one Hono middleware covers it, and everything else (gen_ai spans, logs, outbound fetches) nests under it with clean route names. The `flush` at the end matters: an idle isolate can be suspended, so buffered telemetry has to ship while the request is alive.
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
app.use("*", (c, next) =>
|
|
104
|
+
Sentry.withIsolationScope(() =>
|
|
105
|
+
Sentry.startSpan(
|
|
106
|
+
{
|
|
107
|
+
op: "http.server",
|
|
108
|
+
name: `${c.req.method} ${c.req.path}`,
|
|
109
|
+
forceTransaction: true,
|
|
110
|
+
attributes: {
|
|
111
|
+
"http.request.method": c.req.method,
|
|
112
|
+
"url.path": c.req.path,
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
async (span) => {
|
|
116
|
+
await next();
|
|
117
|
+
span.setAttribute("http.response.status_code", c.res.status);
|
|
118
|
+
},
|
|
119
|
+
).finally(() => Sentry.flush(2000)),
|
|
120
|
+
),
|
|
121
|
+
);
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Then wire a top-level error handler so any error thrown in a route is reported. With Hono, `onError` covers this. Watch out for one gotcha: framework middleware such as `cors()` usually does **not** decorate error responses, so re-add any headers you need on the 500 yourself.
|
|
125
|
+
|
|
126
|
+
```typescript
|
|
127
|
+
app.onError((err, c) => {
|
|
128
|
+
Sentry.captureException(err);
|
|
129
|
+
c.header("access-control-allow-origin", "*"); // cors() doesn't run on error responses
|
|
130
|
+
return c.json({ error: "internal_error" }, 500);
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
(There is a dedicated `@sentry/hono` package, but it is alpha and its Node entry point assumes the app is served by `@hono/node-server`, which is not how Functions run Hono — stick with `onError`.)
|
|
135
|
+
|
|
136
|
+
### 4. Errors are for failures; logs are for the story
|
|
137
|
+
|
|
138
|
+
Long-running agent workloads — the case Neon Functions are built for — typically **catch their own errors and fall back** (retry a different model, return a degraded result) rather than throwing. It's tempting to `captureException` those too, but every recovered retry then opens a warning-level issue: the issue stream fills with things nobody needs to act on, and the terminal failures drown in them.
|
|
139
|
+
|
|
140
|
+
Split by whether someone needs to act:
|
|
141
|
+
|
|
142
|
+
- **`Sentry.captureException` — terminal, needs attention.** The agent exhausted every fallback; an invariant broke. These become issues, group, and alert.
|
|
143
|
+
- **`Sentry.logger.*` — recoverable or narrative.** A model attempt failed and the agent moved on; an input couldn't be fetched; a milestone was reached. Structured log records, searchable by attribute and attached to the request's trace — the story you read _after_ an issue fires.
|
|
144
|
+
|
|
145
|
+
A representative agent that tries several models in order:
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
for (const model of models) {
|
|
149
|
+
try {
|
|
150
|
+
const { text: summary } = await generateText({
|
|
151
|
+
model: neon(model),
|
|
152
|
+
prompt,
|
|
153
|
+
experimental_telemetry: { isEnabled: true },
|
|
154
|
+
});
|
|
155
|
+
Sentry.logger.info("summary produced", { component: "agent", model });
|
|
156
|
+
return c.json({ summary, model });
|
|
157
|
+
} catch (err) {
|
|
158
|
+
lastError = err;
|
|
159
|
+
Sentry.logger.warn("model attempt failed", {
|
|
160
|
+
component: "agent",
|
|
161
|
+
phase: "summarize-attempt",
|
|
162
|
+
model,
|
|
163
|
+
error: String(err),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
Sentry.captureException(lastError, {
|
|
169
|
+
tags: { component: "agent", phase: "summarize-all-failed" },
|
|
170
|
+
contexts: { agent: { attempts: models.length } },
|
|
171
|
+
});
|
|
172
|
+
return c.json({ error: "all models failed" }, 502);
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
- Log **attributes** (the second argument — flat `string | number | boolean` values) are individually searchable and filterable in Sentry's Logs view.
|
|
176
|
+
- On the remaining `captureException` calls, use `tags` for the dimensions you'll filter and group by, and `contexts` for structured per-event detail (`contexts` replaces the legacy `extra`).
|
|
177
|
+
- Logs emitted during a request automatically link to its trace, so from the terminal error you can pull up every preceding attempt.
|
|
178
|
+
|
|
179
|
+
### 5. Trace the agent itself
|
|
180
|
+
|
|
181
|
+
If the function runs a [Vercel AI SDK](https://ai-sdk.dev) agent (see [references/ai-sdk.md](ai-sdk.md)), Sentry captures the full agent → model → tool span hierarchy with token usage per call — `gen_ai.invoke_agent`, `gen_ai.generate_content`, `gen_ai.execute_tool` spans in the request's trace, plus the **Insights → AI Agents** dashboard. On top of the init config from step 1:
|
|
182
|
+
|
|
183
|
+
**Opt each call in** — the AI SDK only emits spans when asked — and **report stream errors**, because `streamText` never throws: failures surface as error parts inside the stream and the HTTP response just ends, so without `onError` a dead agent looks like an empty reply.
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
const result = streamText({
|
|
187
|
+
model: neon(MODEL),
|
|
188
|
+
messages,
|
|
189
|
+
tools,
|
|
190
|
+
experimental_telemetry: { isEnabled: true },
|
|
191
|
+
onError: ({ error }) => {
|
|
192
|
+
Sentry.captureException(error, {
|
|
193
|
+
tags: { component: "agent", phase: "chat-stream" },
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
**Flush when the stream completes.** The middleware's flush runs when the `Response` object is created — before the model finishes — and the gen_ai spans only end with the stream. Ship them from the stream's own finalizer, while the request is still alive:
|
|
200
|
+
|
|
201
|
+
```typescript
|
|
202
|
+
const stream = result.textStream
|
|
203
|
+
.pipeThrough(
|
|
204
|
+
new TransformStream<string, string>({
|
|
205
|
+
async flush() {
|
|
206
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
207
|
+
await Sentry.flush(2000);
|
|
208
|
+
},
|
|
209
|
+
}),
|
|
210
|
+
)
|
|
211
|
+
.pipeThrough(new TextEncoderStream());
|
|
212
|
+
return new Response(stream, {
|
|
213
|
+
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
(Once the runtime's `waitUntil` is no longer a preview stub, `waitUntil(Sentry.flush(2000))` is the cleaner way to express this.)
|
|
218
|
+
|
|
219
|
+
With telemetry enabled the AI SDK records prompts and outputs by default — set `recordInputs: false` / `recordOutputs: false` on the same `experimental_telemetry` object if conversation content must not leave the application. Optionally, group multi-turn chats into a timeline (**Explore → Conversations**) and attribute them to users — set both once per request before the model call:
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
Sentry.setConversationId(chatId);
|
|
223
|
+
Sentry.setUser({ id: userId });
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Direct provider SDKs (`openai`, `@anthropic-ai/sdk`, `@langchain/*`, `@google/genai`) have equivalent Sentry auto-instrumentation, but it patches those modules at import time — which bundling defeats. The Vercel AI SDK path is bundle-safe (the `ai` package emits its own OTel spans), which is why it's the recommended route here. The same caveat applies to other module-patching instrumentation (`pg` spans, for example): if a specific library's spans are missing from a deployed function, bundling is the first thing to check.
|
|
227
|
+
|
|
228
|
+
### Verifying the wiring
|
|
229
|
+
|
|
230
|
+
- **Errors:** temporarily add a route that throws (`app.get("/debug-sentry", () => { throw new Error("sentry test"); })`), hit it, confirm the 500 surfaces as an issue in Sentry, then remove the route.
|
|
231
|
+
- **Logs:** trigger a recoverable failure (e.g. pass a bogus model name to the fallback path) and confirm the `Sentry.logger` records show up in **Explore → Logs**, linked to the same trace.
|
|
232
|
+
- **Traces:** hit a real route and confirm a trace appears (**Explore → Traces**) with the spans you expect — the request root, outbound fetches, and (for agents) `gen_ai.*` spans with token counts. Two things to know before declaring it broken:
|
|
233
|
+
- **Streamed span ingestion lags several minutes behind errors and logs.** An error visible in seconds does not mean its trace is lost — check again after a few minutes.
|
|
234
|
+
- If spans **never** appear while errors and logs flow, check the SDK version — `@sentry/node` <10.67.0 cannot register its tracer against the runtime's pre-created OpenTelemetry API global. Upgrade, or on an older SDK run `delete globalThis[Symbol.for("opentelemetry.js.api.1")]` before `Sentry.init`.
|
|
235
|
+
|
|
236
|
+
## Other Node integrations
|
|
237
|
+
|
|
238
|
+
The same pattern generalizes to any Node integration (structured logging, analytics):
|
|
239
|
+
|
|
240
|
+
1. Initialize once at module scope in a dedicated init module, imported before your handler.
|
|
241
|
+
2. Gate it on an env var so local dev and unconfigured branches are a no-op.
|
|
242
|
+
3. Pass secrets via `--env KEY=VALUE` on deploy or the function's `env` in `neon.ts`.
|
|
243
|
+
|
|
244
|
+
Standard Node SDKs bundle through `neon deploy`'s esbuild without changes — but module-patching auto-instrumentation does not, and anything that registers OpenTelemetry globals contends with the runtime's own registration (see the version note at the top).
|