@neon/skills 2.3.0 → 3.0.0
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/README.md +3 -13
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/skills/neon/SKILL.md +22 -7
- package/skills/neon-ai-gateway/SKILL.md +43 -10
- package/skills/neon-auth/SKILL.md +21 -12
- package/skills/neon-auth/references/managed-auth.md +78 -20
- package/skills/neon-auth/references/oauth-server.md +165 -0
- package/skills/neon-auth/references/self-managed.md +3 -3
- package/skills/neon-functions/SKILL.md +2 -2
- package/skills/neon-functions/references/ai-sdk.md +2 -2
- package/skills/neon-functions/references/mcp.md +32 -23
- package/skills/neon-object-storage/SKILL.md +2 -2
- package/skills/neon-postgres/SKILL.md +26 -15
- package/skills/{neon-postgres-branches/SKILL.md → neon-postgres/references/branching.md} +0 -24
- package/skills/{neon-postgres-egress-optimizer/SKILL.md → neon-postgres/references/egress-optimization.md} +4 -28
- package/skills/neon-postgres/references/hybrid-search.md +135 -6
- package/skills/neon-postgres/references/lakebase-search-drizzle.md +1 -1
- package/skills/neon-postgres/references/vector-search.md +2 -0
- package/skills/neon-realtime/references/queries.md +3 -3
- package/skills/neon-realtime/references/reactivity.md +2 -2
- package/skills/neon-realtime/references/ssr.md +5 -5
- package/skills/neon-realtime/references/subscribing.md +2 -2
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# Managed Better Auth as the OAuth server
|
|
2
|
+
|
|
3
|
+
Use this page when the request is "let MCP clients sign in my users", "protect my MCP server with OAuth", or "let another app or OAuth client call my API on behalf of my users". Managed Better Auth is the OAuth 2.1 / OIDC authorization server (the OAuth provider plugin, beta, available to all Managed projects). Do not move to self-managed Better Auth for this, and keep the app's existing login method.
|
|
4
|
+
|
|
5
|
+
"OAuth server" and "OAuth clients" here are not the social providers (Google, GitHub, Apple) of `neon neon-auth oauth-provider`. Those sign users in to Neon Auth. This page makes Neon Auth issue tokens to other apps.
|
|
6
|
+
|
|
7
|
+
- Docs: https://neon.com/docs/auth/guides/plugins/oauth-provider.md
|
|
8
|
+
- Configuration is per branch: each branch has its own issuer, clients, and settings.
|
|
9
|
+
- Prerequisites: Auth enabled; a login page and a consent page that you host (there is no default UI); the origin of each page on the branch's [trusted domains](../SKILL.md#trusted-domains); at least one protected resource (the MCP server URL, or an API identifier URL).
|
|
10
|
+
|
|
11
|
+
## 1. Enable and configure the server
|
|
12
|
+
|
|
13
|
+
CLI (Console and the API `PATCH .../branches/{branch_id}/auth/plugins/oauth-provider` do the same):
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
# MCP server
|
|
17
|
+
neon neon-auth config oauth-server update --enabled \
|
|
18
|
+
--login-page https://app.example.com/auth/sign-in \
|
|
19
|
+
--consent-page https://app.example.com/auth/consent \
|
|
20
|
+
--mcp-resource https://mcp.example.com/mcp
|
|
21
|
+
|
|
22
|
+
# A non-MCP API instead (or as well)
|
|
23
|
+
neon neon-auth config oauth-server resource add https://api.example.com/reports
|
|
24
|
+
|
|
25
|
+
neon neon-auth config oauth-server get
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- Enabling needs both pages and at least one of `--mcp-resource` or a resource. Resources are absolute `https` URLs (or `http` on loopback) with no query or fragment, and they must not be the Auth host. They do not need to resolve.
|
|
29
|
+
- `--mcp-resource` turns on Client ID Metadata Documents (CIMD): MCP clients that support CIMD identify themselves, so you create no client for them. Turn it off with `--no-mcp-client-id-metadata-documents` to allow only clients you create. Legacy dynamic registration is off by default; leave it off.
|
|
30
|
+
- Keep the MCP server URL in `--mcp-resource`, not in the resources list.
|
|
31
|
+
- `resource add|remove` rewrites the full stored list. `--resources` replaces it.
|
|
32
|
+
|
|
33
|
+
Programmatic equivalents: `neon.auth.oauthServer.get|update` and `neon.auth.oauthClients.*` in `@neon/sdk`, and the `get_auth_oauth_server` / `update_auth_oauth_server` / `*_auth_oauth_client` tools in the Neon MCP server (`neon_auth` scope).
|
|
34
|
+
|
|
35
|
+
## 2. Register clients
|
|
36
|
+
|
|
37
|
+
Skip this for MCP clients that use CIMD. Create managed clients for known apps, for non-MCP resources, or when CIMD is off. Every `--resources` URL must already be configured on the server.
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
neon neon-auth oauth-client create --name "Reports" --type confidential \
|
|
41
|
+
--redirect-uris https://reports.example.com/callback \
|
|
42
|
+
--resources https://api.example.com/reports
|
|
43
|
+
|
|
44
|
+
neon neon-auth oauth-client list
|
|
45
|
+
neon neon-auth oauth-client get <client-id>
|
|
46
|
+
neon neon-auth oauth-client update <client-id> --redirect-uris https://reports.example.com/callback
|
|
47
|
+
neon neon-auth oauth-client rotate-secret <client-id>
|
|
48
|
+
neon neon-auth oauth-client delete <client-id>
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- `confidential` (server-side apps, token endpoint auth `client_secret_basic`) or `public` (SPA, mobile, desktop, CLI; PKCE, no secret). The type cannot change after creation.
|
|
52
|
+
- The `client_secret` of a confidential client is returned only by `create` and `rotate-secret`. Store it in a secret manager or the host's environment variables immediately. The old secret stops working at once on rotation. Never put it in client-side code, the repo, or logs.
|
|
53
|
+
- Redirect URIs must match exactly: `https`, or `http` on `localhost`/`127.0.0.1`/`[::1]` when localhost access is enabled. No fragments, credentials, or custom schemes. Register only the URIs the app uses.
|
|
54
|
+
- At most 100 OAuth clients per project (`OAUTH_CLIENT_LIMIT_REACHED` past that). Run `oauth-client list` before creating more, and reuse or delete a client rather than creating duplicates.
|
|
55
|
+
- `--skip-consent` only for first-party confidential clients you control.
|
|
56
|
+
- A new branch starts with its parent's clients (same IDs and secrets). Rotate secrets on branches that must differ.
|
|
57
|
+
|
|
58
|
+
## 3. Build the login and consent pages
|
|
59
|
+
|
|
60
|
+
Both pages receive the signed authorization query. Use `@neon/auth` 0.8.0 or later: the client forwards that query (`oauth_query`) for you. There is no `auth.oauth.resume()` or `getConsentRequest()` helper; do not call or write one, and do not build consent URLs by hand.
|
|
61
|
+
|
|
62
|
+
```tsx
|
|
63
|
+
// lib/auth/client.ts
|
|
64
|
+
import { createAuthClient } from "@neon/auth";
|
|
65
|
+
export const authClient = createAuthClient(process.env.NEXT_PUBLIC_NEON_AUTH_URL!);
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Login page. Existing sign-in calls (`signIn.email`, `signIn.social`) carry the query automatically. On every load, including the return from a social sign-in, resume if the user already has a session:
|
|
69
|
+
|
|
70
|
+
```tsx
|
|
71
|
+
const { data } = await authClient.getSession();
|
|
72
|
+
if (data?.user) {
|
|
73
|
+
const { error } = await authClient.oauth2.continue({ selected: true });
|
|
74
|
+
if (error) showError("This sign-in link expired. Go back to the app and try again.");
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`continue` navigates to the consent page or back to the client; a 400 means the link expired. After `signIn.email`, skip your own redirect when `data.redirect` is true.
|
|
79
|
+
|
|
80
|
+
Consent page. Show the client name, the redirect URI hosts, and the requested `scope` and `resource` (query parameters), and warn when every redirect URI is loopback:
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
const params = new URLSearchParams(window.location.search);
|
|
84
|
+
const { data: client } = await authClient.oauth2.publicClient({
|
|
85
|
+
query: { client_id: params.get("client_id") ?? "" },
|
|
86
|
+
});
|
|
87
|
+
// Allow / Deny buttons:
|
|
88
|
+
await authClient.oauth2.consent({ accept }); // navigates the browser itself; do not redirect again
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`publicClient` and `consent` need a signed-in user. Send `Content-Security-Policy: frame-ancestors 'none'` on both pages.
|
|
92
|
+
|
|
93
|
+
## 4. Protect an MCP server
|
|
94
|
+
|
|
95
|
+
The user identity is the token's `sub`. Never trust a user id from tool arguments.
|
|
96
|
+
|
|
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
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npm install @neon/oauth @modelcontextprotocol/sdk hono @hono/mcp
|
|
101
|
+
```
|
|
102
|
+
|
|
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
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
import { Hono } from "hono";
|
|
107
|
+
import { StreamableHTTPTransport } from "@hono/mcp";
|
|
108
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
109
|
+
import { createMcpAuth } from "@neon/oauth/mcp";
|
|
110
|
+
import { honoMcp, type McpAuthVariables } from "@neon/oauth/mcp/hono";
|
|
111
|
+
|
|
112
|
+
const mcpAuth = createMcpAuth({
|
|
113
|
+
baseUrl: process.env.NEON_AUTH_BASE_URL!, // the branch's Auth URL
|
|
114
|
+
resource: process.env.MCP_RESOURCE!, // exactly the --mcp-resource value
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const app = new Hono<McpAuthVariables>();
|
|
118
|
+
app.use(honoMcp(mcpAuth, { path: "/mcp" })); // metadata routes + bearer guard
|
|
119
|
+
|
|
120
|
+
app.all("/mcp", async (c) => {
|
|
121
|
+
const userId = c.get("auth").sub; // verified identity; scope every query by it
|
|
122
|
+
const server = new McpServer({ name: "my-mcp", version: "1.0.0" });
|
|
123
|
+
// register tools that close over userId
|
|
124
|
+
const transport = new StreamableHTTPTransport({ sessionIdGenerator: undefined });
|
|
125
|
+
await server.connect(transport);
|
|
126
|
+
return transport.handleRequest(c);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
export default app;
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- Stateless: build the server and transport per request.
|
|
133
|
+
- `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
|
+
- 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
|
+
- 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.
|
|
136
|
+
- Without the SDK, use `jose` against the issuer's JWKS with the same `iss` and `aud` checks. See the docs.
|
|
137
|
+
|
|
138
|
+
## 5. Endpoints and discovery
|
|
139
|
+
|
|
140
|
+
- Issuer = the branch's Auth URL, e.g. `https://ep-example.neonauth.us-east-1.aws.neon.tech/neondb/auth`. Copy it from the Console or `base_url` from `GET .../auth`; do not construct it. It differs per branch, so keep it in per-branch config.
|
|
141
|
+
- Authorization server metadata: `<issuer>/.well-known/oauth-authorization-server` (also `<issuer>/.well-known/openid-configuration`). It lists the authorize, token, and userinfo endpoints, so read them from there.
|
|
142
|
+
- JWKS: `<issuer>/.well-known/jwks.json`. Userinfo: `<issuer>/oauth2/userinfo`.
|
|
143
|
+
- The MCP server serves protected resource metadata (RFC 9728); `honoMcp` does this.
|
|
144
|
+
- Clients must send `resource` on both the authorize and token requests, or the token is opaque and cannot be verified. Access tokens are EdDSA JWTs valid for one hour. Scopes are fixed: `openid`, `profile`, `email`, `offline_access`. Grants are `authorization_code` and `refresh_token`; there is no `client_credentials`.
|
|
145
|
+
|
|
146
|
+
## 6. Verify
|
|
147
|
+
|
|
148
|
+
1. `neon neon-auth config oauth-server get` shows `enabled`, both pages, and the resource.
|
|
149
|
+
2. `curl <issuer>/.well-known/oauth-authorization-server`: `issuer` equals the Auth URL.
|
|
150
|
+
3. `curl -i <mcp-url>` without a token: 401 whose `WWW-Authenticate` points to the protected resource metadata, and that metadata names the issuer.
|
|
151
|
+
4. Run the real flow with MCP Inspector (`npx @modelcontextprotocol/inspector`, Streamable HTTP, the MCP URL) or an MCP client such as Cursor or Claude. Expect: redirect to your login page, then your consent page, then a token, then a successful tool call.
|
|
152
|
+
5. Confirm a tool returns data for the signed-in user only, and that a token for another resource or branch is rejected.
|
|
153
|
+
6. For a managed client, run authorize with PKCE and `resource`, then exchange the code at the token endpoint.
|
|
154
|
+
|
|
155
|
+
Report any step you could not run.
|
|
156
|
+
|
|
157
|
+
## Do NOT
|
|
158
|
+
|
|
159
|
+
- Do not move to self-managed Better Auth or the Better Auth MCP plugin for this. Managed supports it.
|
|
160
|
+
- Do not confuse this with `neon neon-auth oauth-provider` (social login) or Generic OAuth.
|
|
161
|
+
- Do not call `auth.oauth.resume()`, `getConsentRequest()`, or any resume helper. Use `oauth2.continue`, `oauth2.publicClient`, and `oauth2.consent`.
|
|
162
|
+
- Do not put client secrets, or Neon API keys, in browser or mobile code.
|
|
163
|
+
- Do not skip `iss` and `aud` checks, or trust a user id from tool input instead of `sub`.
|
|
164
|
+
- Do not enable dynamic client registration or `--skip-consent` for third-party or public clients.
|
|
165
|
+
- Do not list the MCP server URL under resources instead of `--mcp-resource`.
|
|
@@ -8,7 +8,7 @@ If the app already runs Better Auth, keep that server, its clients, users, and s
|
|
|
8
8
|
|
|
9
9
|
## New self-managed server
|
|
10
10
|
|
|
11
|
-
Host it on the existing app (Vercel route handlers, or similar) when that host already serves `/api/auth`. Use a Neon Function when the auth server should sit next to Postgres,
|
|
11
|
+
Host it on the existing app (Vercel route handlers, or similar) when that host already serves `/api/auth`. Use a Neon Function when the auth server should sit next to Postgres, for example. Function hosting follows the `neon-functions` skill (region, claim, `neon.ts`, `neon deploy --env <file>`).
|
|
12
12
|
|
|
13
13
|
Keep Lakebase Postgres as the auth database. Use `better-auth` and `better-auth/client`. Fetch upstream docs for the **installed** version:
|
|
14
14
|
|
|
@@ -16,9 +16,9 @@ Keep Lakebase Postgres as the auth database. Use `better-auth` and `better-auth/
|
|
|
16
16
|
- https://better-auth.com/docs/concepts/client
|
|
17
17
|
- https://better-auth.com/docs/concepts/plugins
|
|
18
18
|
|
|
19
|
-
Do not pass `plugins` into `@
|
|
19
|
+
Do not pass `plugins` into `@neon/auth`. Replacing only the client package while Managed Auth is still the backend does not add plugins.
|
|
20
20
|
|
|
21
|
-
MCP OAuth (Cursor, Claude, and similar clients self-authorizing)
|
|
21
|
+
The OAuth provider and MCP OAuth (Cursor, Claude, and similar clients self-authorizing) are supported on Managed Auth: [oauth-server.md](oauth-server.md). They are not a reason to self-manage.
|
|
22
22
|
|
|
23
23
|
Function JWT verification, CORS, and direct browser calls: `neon-functions` and https://neon.com/docs/compute/functions/authentication.md.
|
|
24
24
|
|
|
@@ -65,7 +65,7 @@ Check this precondition before setting anything up: Neon Functions is currently
|
|
|
65
65
|
|
|
66
66
|
## Architecture: Where Functions Fit
|
|
67
67
|
|
|
68
|
-
Neon (Functions included) is **backend primitives, not full-stack app hosting**. Host your app on **Vercel** (or Netlify, or
|
|
68
|
+
Neon (Functions included) is **backend primitives, not full-stack app hosting**. Host your app on a frontend hosting provider like **Vercel** (or Netlify, Cloudflare, etc.), or serve a small static page from a `public_read` bucket behind a CDN (see the `neon-object-storage` skill for caching); Functions are the long-running, stateful slice of your backend that lives next to your data. They compose with that platform in two ways:
|
|
69
69
|
|
|
70
70
|
- **Add a Function to a full-stack app.** Your Next.js / TanStack Start app on Vercel (or Netlify) owns UI, auth (Managed Auth, Better Auth, Clerk, or another IdP), and talks directly to Lakebase Postgres and Object Storage. Add a Function as a Hono API layer for the web app and other clients, or for one job next to the data: Object Storage uploads, AI agents, Discord bots, WebSocket or SSE servers. (See [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks) for the client-direct pattern.)
|
|
71
71
|
- **Run the whole backend control plane on Functions.** Especially when the frontend is **client-only** — TanStack Router, React Router in client mode, and similar SPAs hosted on Vercel or Netlify — the client calls Functions **directly**. Build REST APIs and request/response agents, host **MCP servers**, and run anything stateful or that belongs close to Postgres and Object Storage.
|
|
@@ -628,7 +628,7 @@ app.all("/mcp", async (c) => {
|
|
|
628
628
|
});
|
|
629
629
|
```
|
|
630
630
|
|
|
631
|
-
Because the function's URL is public, **authenticate before connecting the transport** —
|
|
631
|
+
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`.
|
|
632
632
|
|
|
633
633
|
## Integrations and Observability
|
|
634
634
|
|
|
@@ -97,8 +97,8 @@ const result = streamText({
|
|
|
97
97
|
messages,
|
|
98
98
|
tools: {
|
|
99
99
|
image_generation: neon.tools.imageGeneration({
|
|
100
|
+
model: "gpt-image-2", // or gpt-image-1.5, gpt-image-1-mini
|
|
100
101
|
outputFormat: "jpeg",
|
|
101
|
-
quality: "low", // the gateway caps a response near 640 KB — keep images small
|
|
102
102
|
size: "1024x1024",
|
|
103
103
|
}),
|
|
104
104
|
},
|
|
@@ -117,7 +117,7 @@ const result = streamText({
|
|
|
117
117
|
});
|
|
118
118
|
```
|
|
119
119
|
|
|
120
|
-
|
|
120
|
+
Always stream image generation with `streamText`. A non-streaming response whose image is over 655,360 bytes fails with `400: The response content length cannot be greater than 655360 bytes long`; streamed images have no such cap. See the `neon-ai-gateway` skill's Generate Images section.
|
|
121
121
|
|
|
122
122
|
## 4. Call it directly from the client (don't proxy the stream)
|
|
123
123
|
|
|
@@ -89,43 +89,51 @@ Key points:
|
|
|
89
89
|
> [!WARNING]
|
|
90
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
91
|
|
|
92
|
-
|
|
92
|
+
Use **Managed Better Auth (Neon Auth) as the OAuth server** and guard the Function with `@neon/oauth` (0.3.0 or later). MCP clients that support OAuth (Cursor, Claude, ChatGPT) discover the server, sign the user in on a login and consent page you host, and call `/mcp` with an access token. Keep the app's existing login; the OAuth server sits beside it. The full path (CLI setup, clients, pages, verification) is [neon-auth references/oauth-server.md](https://neon.com/docs/ai/skills/neon-auth/references/oauth-server.md).
|
|
93
93
|
|
|
94
|
-
### Option 1 — OAuth via
|
|
94
|
+
### Option 1 — OAuth via Managed Better Auth (best for third-party clients)
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
Configure the server once:
|
|
97
97
|
|
|
98
|
-
|
|
98
|
+
```bash
|
|
99
|
+
neon neon-auth config oauth-server update --enabled \
|
|
100
|
+
--login-page https://app.example.com/auth/sign-in \
|
|
101
|
+
--consent-page https://app.example.com/auth/consent \
|
|
102
|
+
--mcp-resource https://<your-function-url>/mcp
|
|
103
|
+
```
|
|
104
|
+
|
|
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:
|
|
99
106
|
|
|
100
107
|
```typescript
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
108
|
+
import { createMcpAuth } from "@neon/oauth/mcp";
|
|
109
|
+
import { honoMcp, type McpAuthVariables } from "@neon/oauth/mcp/hono";
|
|
110
|
+
|
|
111
|
+
const mcpAuth = createMcpAuth({
|
|
112
|
+
baseUrl: process.env.NEON_AUTH_BASE_URL!, // the branch's Auth URL
|
|
113
|
+
resource: process.env.MCP_RESOURCE!, // exactly the --mcp-resource value
|
|
114
|
+
});
|
|
105
115
|
|
|
106
|
-
const
|
|
116
|
+
const app = new Hono<McpAuthVariables>();
|
|
117
|
+
app.use(honoMcp(mcpAuth, { path: "/mcp" }));
|
|
107
118
|
|
|
108
119
|
app.all("/mcp", async (c) => {
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
if (!mcpServer.isConnected()) await mcpServer.connect(transport);
|
|
117
|
-
return transport.handleRequest(c); // scope tools to session.userId
|
|
120
|
+
const userId = c.get("auth").sub;
|
|
121
|
+
// Build a McpServer whose tools close over userId; stateless transport per request.
|
|
122
|
+
const server = createServer(userId);
|
|
123
|
+
const transport = new StreamableHTTPTransport({ sessionIdGenerator: undefined });
|
|
124
|
+
await server.connect(transport);
|
|
125
|
+
return transport.handleRequest(c);
|
|
118
126
|
});
|
|
119
127
|
```
|
|
120
128
|
|
|
121
|
-
|
|
129
|
+
A per-request server and transport replace the module-scope server above because tools need the caller's `sub`; keep the `pg` pool at module scope. 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.
|
|
122
130
|
|
|
123
|
-
### Option 2 — API key or session JWT
|
|
131
|
+
### Option 2 — API key or session JWT (simplest)
|
|
124
132
|
|
|
125
|
-
When the callers are your own agents/services or a personal MCP server, you don't need the
|
|
133
|
+
When the callers are your own agents/services or a personal MCP server, you don't need the OAuth flow. Either:
|
|
126
134
|
|
|
127
|
-
- **API keys** —
|
|
128
|
-
- **Session JWT** —
|
|
135
|
+
- **API keys** — issue and store your own keys, and have the function verify the `Authorization: Bearer <key>` (or an `x-api-key` header) on every request; or
|
|
136
|
+
- **Session JWT** — verify a Managed Auth JWT (`NEON_AUTH_JWKS_URL`, issuer from `NEON_AUTH_BASE_URL`) with `jose`, the same pattern used for the [agent backend](../SKILL.md#functions-as-an-agent-backend-nextjs-and-similar-frameworks).
|
|
129
137
|
|
|
130
138
|
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
139
|
|
|
@@ -139,6 +147,7 @@ app.all("/mcp", async (c) => {
|
|
|
139
147
|
});
|
|
140
148
|
```
|
|
141
149
|
|
|
150
|
+
|
|
142
151
|
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
152
|
|
|
144
153
|
## Testing
|
|
@@ -43,7 +43,7 @@ Reach for Neon Object Storage for the files an app and its users produce — upl
|
|
|
43
43
|
- **They want safe, throwaway environments.** Upload, overwrite, and delete files in a preview/CI branch without any risk to production data, then drop the branch.
|
|
44
44
|
- **They want standard S3 tooling.** It's built on S3 semantics and speaks the S3 API, so the AWS SDKs, `boto3`, the AWS CLI, and presigned URLs all work — reliable and familiar, with no proprietary client.
|
|
45
45
|
|
|
46
|
-
If the files in question ship with the app itself — HTML, JS bundles, CSS, the images in `public/` — that's static web hosting
|
|
46
|
+
If the files in question ship with the app itself — HTML, JS bundles, CSS, the images in `public/` — that's static web hosting. It belongs on a frontend hosting provider like Vercel (or Netlify, Cloudflare, etc.), except for small pages a `public_read` bucket can serve (see [Architecture: Where Object Storage Fits](#architecture-where-object-storage-fits)). Public assets that are served from a bucket want a CDN in front of them (see [Architecture: Where Object Storage Fits](#architecture-where-object-storage-fits)).
|
|
47
47
|
|
|
48
48
|
## What It Does
|
|
49
49
|
|
|
@@ -61,7 +61,7 @@ Check this precondition before setting anything up: Neon Object Storage is curre
|
|
|
61
61
|
Neon (Object Storage included) is **backend primitives, not full-stack app hosting**. Object Storage holds the files the app and its users produce — uploads, attachments, avatars, documents, generated images, backups — keyed from Postgres rows on the same branch. Two boundaries follow from that:
|
|
62
62
|
|
|
63
63
|
- **Put a CDN in front of public assets.** A `public_read` object is read anonymously at `${AWS_ENDPOINT_URL_S3}/<bucket>/<object-key>` — the branch's storage endpoint, injected as an env var (see [Environment Variables](#environment-variables)). For assets a browser loads on every page view — avatars, product images, anything hot — use that as the origin for a Cloudflare or Vercel CDN, and set `Cache-Control` on `PutObject` so the edge knows how long to hold each object. A cached object is only as fresh as its key, so write each version to a new key (`avatars/<user-id>/<uuid>.jpg`) and repoint the key stored in Postgres, rather than overwriting one key and waiting out the TTL. The endpoint is branch-scoped, so a production CDN points at the production branch while preview branches read their own endpoint directly rather than sharing a cache. Private buckets stay on presigned URLs instead, which carry their signature in the query string.
|
|
64
|
-
- **
|
|
64
|
+
- **Static hosting: a bucket for small pages, a frontend host for the app.** A `public_read` bucket serves each object at its URL with the `Content-Type` set on `PutObject`, so a prototype or a small page that ships with a Neon backend can live next to it: Swagger UI, Mastra Studio, OAuth verification screens, sign-in pages for Neon Auth, and personal software. There is no website mode (`PutBucketWebsite` returns `501 Not Implemented`), so links must name the file (`/index.html`), and there are no SPA fallbacks or custom domains. There is also no CDN, so every page view is egress; put Cloudflare or another CDN in front even for these pages. Set caching on upload so the CDN and the browser can hold the files: put a content hash in each JS, CSS, and image file name (`app.3f9a1c.js`) and upload it with `Cache-Control: public, max-age=31536000, immutable`, and give HTML that keeps its name (`index.html`) a short `max-age` so a new upload shows up. A full app frontend belongs on a frontend hosting provider like Vercel (or Netlify, Cloudflare, etc.), which ships static hosting and a CDN.
|
|
65
65
|
|
|
66
66
|
## Setup
|
|
67
67
|
|
|
@@ -2,15 +2,18 @@
|
|
|
2
2
|
name: neon-postgres
|
|
3
3
|
description: >-
|
|
4
4
|
Guides and best practices for working with Lakebase Postgres on Neon:
|
|
5
|
-
connections, pooled vs direct, schema migrations, branching
|
|
5
|
+
connections, pooled vs direct, schema migrations, branching (including
|
|
6
|
+
schema-only, reset-from-parent, and branch-per-PR workflows), autoscaling,
|
|
6
7
|
scale-to-zero, instant restore, read replicas, IP allow lists, logical
|
|
7
|
-
replication, and Lakebase Search. Use when the work is
|
|
8
|
-
DATABASE_URL, SQL, schema, inspect, or search. New backends, Auth,
|
|
9
|
-
Functions, and LLM calls go to the parent `neon` skill. Live queries,
|
|
10
|
-
UIs, and realtime data go to `neon-realtime`. Also use for
|
|
11
|
-
"@neondatabase/serverless", "@
|
|
12
|
-
"
|
|
13
|
-
|
|
8
|
+
replication, egress optimization, and Lakebase Search. Use when the work is
|
|
9
|
+
an existing DATABASE_URL, SQL, schema, inspect, or search. New backends, Auth,
|
|
10
|
+
files, Functions, and LLM calls go to the parent `neon` skill. Live queries,
|
|
11
|
+
reactive UIs, and realtime data go to `neon-realtime`. Also use for
|
|
12
|
+
"@neondatabase/serverless", "@neon/neon-js", "neon inspect db", "Neon
|
|
13
|
+
branch", "schema-only branch", "reset branch", "branch per PR", high database
|
|
14
|
+
bills, network transfer or egress, SELECT * optimization, query overfetching,
|
|
15
|
+
"semantic search", "vector search", "full-text search", "BM25", or "hybrid
|
|
16
|
+
search".
|
|
14
17
|
metadata:
|
|
15
18
|
parent: neon
|
|
16
19
|
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres
|
|
@@ -30,7 +33,7 @@ Lakebase Postgres is the database at the core of Neon. It runs on the lakebase a
|
|
|
30
33
|
|
|
31
34
|
It is the same database whether you reach it through Neon or through Databricks; this skill covers the Neon access path.
|
|
32
35
|
|
|
33
|
-
Login, users, sessions, and `@
|
|
36
|
+
Login, users, sessions, and `@neon/auth` belong in `neon-auth`.
|
|
34
37
|
|
|
35
38
|
Live queries, reactive UIs, and realtime data belong in `neon-realtime`.
|
|
36
39
|
|
|
@@ -89,11 +92,7 @@ Key points:
|
|
|
89
92
|
|
|
90
93
|
Link: https://neon.com/docs/introduction/branching.md
|
|
91
94
|
|
|
92
|
-
For detailed branch creation workflows (normal vs schema-only branches, reset-from-parent, CLI/MCP selection
|
|
93
|
-
|
|
94
|
-
```bash
|
|
95
|
-
neon skills -s neon-postgres-branches -y
|
|
96
|
-
```
|
|
95
|
+
For detailed branch creation workflows (normal vs schema-only branches, reset-from-parent, CLI/MCP selection, and CI/CD patterns), read [Branching workflows](references/branching.md).
|
|
97
96
|
|
|
98
97
|
## Migrations
|
|
99
98
|
|
|
@@ -101,6 +100,14 @@ Test a migration on a branch of production, against production-like data, before
|
|
|
101
100
|
|
|
102
101
|
Use a **direct (non-pooled)** connection string when you run the migration, not a pooled one. `neon connection-string` returns the direct string by default; make sure the hostname does not include the `-pooler` suffix.
|
|
103
102
|
|
|
103
|
+
## Egress Optimization
|
|
104
|
+
|
|
105
|
+
Use this when a user reports high database bills, unexpected network transfer, egress spikes, query overfetching, or wants a cost-efficiency review of database query patterns.
|
|
106
|
+
|
|
107
|
+
Before editing code, read [Egress optimization](references/egress-optimization.md). Audit all five patterns: unused columns, missing pagination, repeated static reads, application-side aggregation, and JOIN duplication. Do not stop after fixing `SELECT *`.
|
|
108
|
+
|
|
109
|
+
Work in four steps: diagnose which queries transfer the most data, analyze the code behind them, fix the anti-patterns, then verify that behavior is preserved and transfer drops.
|
|
110
|
+
|
|
104
111
|
## Troubleshooting and Neon-Specific Performance
|
|
105
112
|
|
|
106
113
|
Use Neon's predefined, read-only diagnostics before writing catalog queries by hand. The Neon CLI `neon inspect db` subcommands and the Neon MCP server's `inspect_database` tool run the same checks.
|
|
@@ -203,6 +210,10 @@ Key points:
|
|
|
203
210
|
|
|
204
211
|
Link: https://neon.com/docs/introduction/scale-to-zero.md
|
|
205
212
|
|
|
213
|
+
### Keep hot reads off Postgres
|
|
214
|
+
|
|
215
|
+
Scale to zero only suspends an idle compute. When the same rarely changing rows (config, categories, feature flags) are read on every request, cache them outside Postgres, for example in [Upstash Redis](https://upstash.com/docs/redis) with a TTL. Cached reads cut egress and cold-start latency, and let an otherwise idle compute stay suspended.
|
|
216
|
+
|
|
206
217
|
## Instant Restore
|
|
207
218
|
|
|
208
219
|
Use this when the user needs point-in-time recovery or wants to restore data state without traditional backup restore workflows.
|
|
@@ -262,7 +273,7 @@ Use Lakebase Search for semantic, full-text, and hybrid search:
|
|
|
262
273
|
|
|
263
274
|
- For semantic search, including generating embeddings with the Neon AI Gateway, read [Vector search](references/vector-search.md).
|
|
264
275
|
- For full-text search with BM25 ranking, read [Full-text search](references/full-text-search.md).
|
|
265
|
-
- For combining semantic and lexical results, read [Hybrid search](references/hybrid-search.md).
|
|
276
|
+
- For combining semantic and lexical results with fusion or reranking, read [Hybrid search](references/hybrid-search.md).
|
|
266
277
|
- For managing any of the above through Drizzle ORM, read [Managing Lakebase Search with Drizzle](references/lakebase-search-drizzle.md).
|
|
267
278
|
|
|
268
279
|
Links:
|
|
@@ -1,27 +1,3 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: neon-postgres-branches
|
|
3
|
-
description: >-
|
|
4
|
-
Choose and create the right Neon branch type for testing and development.
|
|
5
|
-
Use when users ask about Neon branching, migration testing with real data,
|
|
6
|
-
isolated test environments, schema-only branch workflows for sensitive data,
|
|
7
|
-
resetting a branch from its parent, branch expiration and CI/CD branch
|
|
8
|
-
lifecycles, or branch creation via Neon CLI or Neon MCP. Triggers include
|
|
9
|
-
"Neon branch", "test migrations safely", "branch production data",
|
|
10
|
-
"schema-only branch", "reset branch", "branch per PR" and
|
|
11
|
-
"sensitive data testing".
|
|
12
|
-
metadata:
|
|
13
|
-
parent: neon
|
|
14
|
-
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres-branches
|
|
15
|
-
---
|
|
16
|
-
|
|
17
|
-
**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
|
|
18
|
-
|
|
19
|
-
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
|
|
20
|
-
|
|
21
|
-
```bash
|
|
22
|
-
neon skills -s neon -y
|
|
23
|
-
```
|
|
24
|
-
|
|
25
1
|
# Lakebase Postgres Branching
|
|
26
2
|
|
|
27
3
|
**Outcome:** a created Neon branch — or a clear, actionable next step if creation cannot proceed. Choose the correct branch type, then execute branch creation with the CLI (or MCP where the CLI isn't usable).
|
|
@@ -1,27 +1,3 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: neon-postgres-egress-optimizer
|
|
3
|
-
description: >-
|
|
4
|
-
Diagnose and fix excessive Postgres egress (network data transfer) in a codebase.
|
|
5
|
-
Use when a user mentions high database bills, unexpected data transfer costs,
|
|
6
|
-
network transfer charges, egress spikes, "why is my Neon bill so high",
|
|
7
|
-
"database costs jumped", SELECT * optimization, query overfetching,
|
|
8
|
-
reduce Neon costs, optimize database usage, or wants to reduce data sent
|
|
9
|
-
from their database to their application. Also use when reviewing query
|
|
10
|
-
patterns for cost efficiency, even if the user doesn't explicitly mention
|
|
11
|
-
egress or data transfer.
|
|
12
|
-
metadata:
|
|
13
|
-
parent: neon
|
|
14
|
-
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres-egress-optimizer
|
|
15
|
-
---
|
|
16
|
-
|
|
17
|
-
**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
|
|
18
|
-
|
|
19
|
-
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
|
|
20
|
-
|
|
21
|
-
```bash
|
|
22
|
-
neon skills -s neon -y
|
|
23
|
-
```
|
|
24
|
-
|
|
25
1
|
# Postgres Egress Optimizer
|
|
26
2
|
|
|
27
3
|
Guide the user through diagnosing and fixing application-side query patterns that cause excessive data transfer (egress) from their Postgres database. Most high egress bills come from the application fetching more data than it uses.
|
|
@@ -44,13 +20,13 @@ If this errors, the extension needs to be created:
|
|
|
44
20
|
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
|
|
45
21
|
```
|
|
46
22
|
|
|
47
|
-
On Neon the extension is available by default, but it may still need this CREATE EXTENSION step.
|
|
23
|
+
On Neon the extension is available by default, but it may still need this CREATE EXTENSION step. Ask before creating it because installing an extension modifies the database.
|
|
48
24
|
|
|
49
25
|
### Handle empty stats
|
|
50
26
|
|
|
51
27
|
Stats are cleared when a Neon compute scales to zero and restarts. If the stats are empty or the compute recently woke up:
|
|
52
28
|
|
|
53
|
-
1.
|
|
29
|
+
1. Ask before resetting the stats, then start a clean measurement window with `SELECT pg_stat_statements_reset();`
|
|
54
30
|
2. Let the application run under representative traffic for at least an hour.
|
|
55
31
|
3. Return and run the diagnostic queries below.
|
|
56
32
|
|
|
@@ -171,7 +147,7 @@ When adding pagination, check whether the consuming client already supports pagi
|
|
|
171
147
|
|
|
172
148
|
Look for queries with extremely high call counts relative to other queries. Common examples: configuration tables, category lists, feature flags, user role definitions.
|
|
173
149
|
|
|
174
|
-
**Fix:** Add a caching layer between the application and the database so it avoids hitting the database on every request.
|
|
150
|
+
**Fix:** Add a caching layer between the application and the database so it avoids hitting the database on every request. Reuse a cache the app already has. Otherwise, a serverless Redis such as [Upstash Redis](https://upstash.com/docs/redis) works from serverless and edge runtimes without connection management.
|
|
175
151
|
|
|
176
152
|
### Application-side aggregation
|
|
177
153
|
|
|
@@ -223,7 +199,7 @@ After applying fixes:
|
|
|
223
199
|
|
|
224
200
|
1. **Run existing tests** to confirm nothing broke.
|
|
225
201
|
2. **Check the responses** — make sure the API still returns the same data shape. Column selection and pagination changes can break clients that depend on specific fields or full result sets.
|
|
226
|
-
3. **Measure the improvement** — if pg_stat_statements data is available,
|
|
202
|
+
3. **Measure the improvement** — if pg_stat_statements data is available, ask before resetting it (`SELECT pg_stat_statements_reset();`), let traffic run, then re-run the diagnostic queries to compare before and after.
|
|
227
203
|
|
|
228
204
|
## Neon Infrastructure as Code (`neon.ts`)
|
|
229
205
|
|