@nexgen-os/mcp 0.0.0-stage → 0.4.1

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 CHANGED
@@ -1,3 +1,221 @@
1
- # Temporary Holding Version
1
+ # @nexgen-os/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [Model Context Protocol](https://modelcontextprotocol.io) server for
4
+ [Nexgen OS](https://github.com/nexgen-os/nexgen-os). It lets an AI agent
5
+ work on the energy assets in your own Postgres: find an organisation and its
6
+ projects, add a participant with its place, declare its meter, install its
7
+ devices, import its readings, size a PV system or a battery, estimate a
8
+ yield, settle a sharing, read the indicators and propose what to do —
9
+ **as you**, under the row level security of your own installation
10
+ ([decision 0039](../../docs/decisions/0039-an-agent-is-a-user-of-the-model.md),
11
+ [decision 0046](../../docs/decisions/0046-a-key-acts-as-its-issuer-an-agent-reaches-the-database-as-the-person.md)).
12
+
13
+ There are two ways to reach it, and they are the same server: started by a
14
+ client over stdio, or reached by URL over Streamable HTTP. It follows the
15
+ shape and the conventions of the MCP server of
16
+ [Ekwo OS](https://github.com/Ekwo-ai/ekwo-os), so one person configures
17
+ both the same way.
18
+
19
+ ## Locally, over stdio
20
+
21
+ ```sh
22
+ npx -y @nexgen-os/mcp@latest
23
+ ```
24
+
25
+ For a client that launches its own servers — Claude Desktop, Claude Code,
26
+ any editor that reads `.mcp.json`:
27
+
28
+ ```json
29
+ {
30
+ "mcpServers": {
31
+ "nexgen": {
32
+ "command": "npx",
33
+ "args": ["-y", "@nexgen-os/mcp@latest"],
34
+ "env": {
35
+ "NEXGEN_DB_URL": "postgresql://…",
36
+ "NEXGEN_API_KEY": "ngk_…"
37
+ }
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ The key is issued by a person who holds `members.manage` on the organisation (an owner), signed in:
44
+ `nexgen-os key create --organisation <id> --name "My agent"` (add `--write`
45
+ for a key that writes). Keep `@latest` in the command: from inside a clone
46
+ of the repository, a bare `npx @nexgen-os/mcp` finds the unbuilt workspace.
47
+
48
+ From a clone of the repository, `npx tsx modules/mcp.ts` starts the same
49
+ server with the computations of the modules shipped there (sizing, yields,
50
+ settlements), which the package on npm does not carry yet.
51
+
52
+ ## What it is, and what it is not
53
+
54
+ The server holds no privileges of its own. Every tool runs in one
55
+ transaction that first says who it acts as, then takes the `authenticated`
56
+ role, so everything it can do is exactly what that person can do: a viewer
57
+ reads and cannot write, a member of one organisation does not see another.
58
+ None of that is checked in this package — the policies of the schema
59
+ decide, and this server reports what they answered.
60
+
61
+ Three things it will never do:
62
+
63
+ - **Write a figure.** A yield, a sizing, a settlement and an indicator are
64
+ computed by their module and kept with their provenance; the tools call
65
+ the module and read back what it kept. Every write goes through the
66
+ schema's function for its gesture (`create_project()`, `join_project()`,
67
+ `declare_meter()`, `install_device()`, `store()`, `kpis.compute()`,
68
+ `actions.propose()`…); no tool writes SQL of its own.
69
+ - **Write when you did not allow it.** It reads by default. Writing is
70
+ allowed by the person: `NEXGEN_WRITE=1` in the environment they wrote, a
71
+ key with `write`, or the scope `energy.write` on the connection they
72
+ approved. Otherwise the transaction is read only, and the database itself
73
+ refuses the write (`read_only`).
74
+ - **Use a `service_role` key.** It would work, and that is the objection: it
75
+ bypasses every policy, so the agent would answer for organisations its
76
+ user was never invited to. The server refuses to start with one, in any
77
+ slot.
78
+
79
+ ## Configuration
80
+
81
+ One connection, and exactly one person to act as.
82
+
83
+ | Variable | Meaning |
84
+ |---|---|
85
+ | `NEXGEN_DB_URL` | The connection string of the database (on Supabase: the session pooler or the direct connection) |
86
+ | `NEXGEN_API_KEY` | A key of Nexgen OS (`ngk_…`): its issuer, within the key's organisation, read only unless the key carries `write` |
87
+ | `NEXGEN_ACCESS_TOKEN` | A person's session on the installation, verified by its Supabase Auth with the two below |
88
+ | `SUPABASE_URL` / `SUPABASE_ANON_KEY` | The project and its anon (publishable) key, to verify a session. A `service_role` key is refused |
89
+ | `NEXGEN_ACT_AS_USER_ID` | The `auth.users` id of a person, for a self-hosted installation whose owner holds the connection anyway |
90
+ | `NEXGEN_WRITE` | `1` lets the agent write; it reads otherwise |
91
+ | `NEXGEN_GEOCODERS` | Optional. The geocoders an address may be sent to, by connector (`ban,photon`); none by default, and an address is then refused as `geocoder_not_configured` while a place given as a point is not. Each is keyed by the countries and regions its `sources` row serves, so the register of the country is asked first ([`geocoders.ts`](../core/src/geocoders.ts)) |
92
+ | `NEXGEN_GEOCODER_USER_AGENT` | The user agent a public instance asks for (Nominatim) |
93
+ | `NEXGEN_ENGINE_<NAME>` | The command of a program connector (`pvlib`, a sharing program): a tool names an engine, never its command |
94
+
95
+ **Started with nothing set**, the server still starts, still lists its
96
+ tools, and every call answers `not_configured` with the variables to set.
97
+ Only absence is forgiven: a `service_role` key, two people to act as or a
98
+ malformed id are refused at start.
99
+
100
+ ## Over HTTP: hosting it for others
101
+
102
+ The hosted server is an operated service, not part of this repository; this
103
+ section says how anyone hosts one. `nexgen-mcp --http` serves the
104
+ **Streamable HTTP** transport of MCP at `<origin>/mcp`:
105
+
106
+ ```sh
107
+ NEXGEN_DB_URL='postgresql://…' SUPABASE_URL='https://<ref>.supabase.co' \
108
+ SUPABASE_ANON_KEY='<anon key>' NEXGEN_MCP_ORIGIN='https://mcp.example.org' \
109
+ npx -y @nexgen-os/mcp@latest --http --port 8787
110
+ ```
111
+
112
+ It is **stateless**: each request builds a server, answers in JSON and
113
+ closes it, with no session id and nothing kept, so it runs on a function
114
+ platform, behind a load balancer, or in one process. A `GET` on the
115
+ endpoint is `405`: this server never speaks first. `handleHttpRequest()`
116
+ (a web `Request` in, a `Response` out) and `handleNodeRequest()` (for
117
+ `node:http`) are the same handler, for a host that mounts it itself.
118
+
119
+ **Who a request acts as is decided per request**, from its bearer:
120
+
121
+ - **A key of Nexgen OS** (`Authorization: Bearer ngk_…`), presented to the
122
+ database by `use_api_key()`: its issuer, within its organisation.
123
+ - **A person's access token**, verified by the installation's Supabase Auth;
124
+ it writes only when the token carries the scope `energy.write`.
125
+
126
+ ### Authorization: what a remote client discovers
127
+
128
+ A remote client — claude.ai, or any other that adds servers by URL —
129
+ follows the [authorization part of the MCP
130
+ specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization),
131
+ as it does for Ekwo OS's hosted server:
132
+
133
+ 1. A request without a bearer is answered `401` with
134
+ `WWW-Authenticate: Bearer resource_metadata="<origin>/.well-known/oauth-protected-resource", scope="energy"`.
135
+ 2. `/.well-known/oauth-protected-resource` is the protected-resource
136
+ metadata of **RFC 9728**: the resource `<origin>/mcp`, its authorization
137
+ server, the scopes `energy` (read) and `energy.write` (write).
138
+ 3. The authorization server publishes its metadata (**RFC 8414**), with a
139
+ registration endpoint where the client registers itself (**RFC 7591**,
140
+ so it needs no credentials of its own), then sends the person to approve
141
+ the connection — and choose whether the agent may write.
142
+
143
+ By default the authorization server is **the installation's own Supabase
144
+ Auth** (`<SUPABASE_URL>/auth/v1`), its OAuth 2.1 server with dynamic client
145
+ registration turned on in the project's authentication settings; the
146
+ tokens it issues are the person's sessions, which this server verifies.
147
+ A host that is its own authorization server names itself instead
148
+ (`authorizationServers`) and serves its metadata here through
149
+ `authorizationServerMetadata()`: the code flow with PKCE `S256`, public
150
+ clients, refresh tokens, and its registration endpoint. Either way the
151
+ database stays the only place that decides what may be read or written.
152
+
153
+ An agent without a browser can start from
154
+ `<origin>/.well-known/oauth-protected-resource`.
155
+
156
+ ## The tools
157
+
158
+ Every tool runs as the person. Read tools are annotated `readOnlyHint`;
159
+ `actions_validate` and `revoke_api_key` are annotated destructive, so a
160
+ client can ask before calling them.
161
+
162
+ | Tool | What it does |
163
+ |---|---|
164
+ | `status` | The schema version, who you act as, the modules installed, the organisations you read with your role |
165
+ | `list_organisations` · `list_projects` · `list_participants` · `list_meters` · `list_devices` · `list_series` | The six objects of the core, filtered by their parent |
166
+ | `get_object` | One object by its kind and id, with its attributes in force (`attributes_of()`) |
167
+ | `read_series` | The values of a series per bucket of a regular step (`resample()`) |
168
+ | `parameter_of` | A parameter of an object through the cascade of defaults (`parameter_of()`); null when nothing decides it |
169
+ | `list_api_keys` | The keys of an organisation you manage (`members.manage`), never a secret |
170
+ | `create_project` | Opens a project in an organisation, in the country the person names (`create_project()`) |
171
+ | `add_participant` | A participant joins a project with its place (`join_project()`), given as a point or found through the configured geocoder chain |
172
+ | `declare_meter` | A meter by its identifier in a scheme, which checks it (`declare_meter()`) |
173
+ | `install_device` | A device, from a product of the catalogue or with a stated power (`install_device()`) |
174
+ | `store_series` | Values through `store()`, each dated at the start of its interval, with their source |
175
+ | `import_series` | The readings of a file read by its format library — `homeassistant` — written through `store()` |
176
+ | `create_api_key` · `revoke_api_key` | A key issued by a person who holds `members.manage`, signed in, with capabilities they hold (`data.read`, `data.write`…), and its withdrawal; a key does not issue keys |
177
+ | `list_modules` | The modules installed and the tools each adds here |
178
+
179
+ **The modules.** A module installed on the database gets its tools, under
180
+ its code as a prefix; a module that is not installed offers none.
181
+
182
+ | Module | Tools |
183
+ |---|---|
184
+ | `kpis` | `kpis_of` (the indicators of an object, `kpis.of()`), `kpis_compute` (one kept as a figure, `kpis.compute()`) |
185
+ | `solar` | `solar_estimates`, `solar_size` (a named criterion, [0045](../../docs/decisions/0045-to-size-is-one-gesture.md)), `solar_estimate_yield` (a named profile) |
186
+ | `battery` | `battery_estimates`, `battery_size` |
187
+ | `charging` | `charging_sessions`, `charging_limit`, `charging_size` |
188
+ | `community` | `community_settlements`, `community_settle` (by the sharing engine the person configured) |
189
+ | `actions` | `actions_of_project`, `actions_propose` (`source = 'agent'`, resting on an estimate), `actions_validate` |
190
+
191
+ Sizing, yields and settlements are code of their module rather than
192
+ functions of the schema. A host hands them in (`buildServer(session, {
193
+ computations })`); `modules/computations.ts` is that list for the modules of
194
+ this repository, and without it these tools answer `computation_not_loaded`.
195
+
196
+ ## Conventions
197
+
198
+ - **Refusals travel unchanged.** `time_zone_required:`, `read_only:`,
199
+ `api_key_revoked:` and the rest arrive with the message the database
200
+ raised, plus a sentence saying what to do. They are answers, not obstacles
201
+ to route around ([0038](../../docs/decisions/0038-everything-raises-by-name.md)).
202
+ - **Dates are ISO**, a value is dated at the start of its interval, an
203
+ azimuth is in degrees clockwise from true north. Identifiers are uuids.
204
+ - **Nothing is assumed**: a country, a currency, a time zone, a sizing
205
+ criterion is the person's, or a pack's.
206
+ - **The schema is checked first**: a database older than `nexgenOs.schemaMin`
207
+ is refused by name (`schema_too_old`).
208
+
209
+ ## Testing it
210
+
211
+ The automated tests run every kind of tool against the real schema in
212
+ Postgres compiled to WebAssembly (`tests/mcp/`), the OAuth discovery
213
+ documents and the refusals included. By hand: install on a project you can
214
+ throw away (`npx nexgen-os init`), issue a key, point a client at it with
215
+ the block above, and ask for a first session — "list my organisations",
216
+ "add a participant at this address to the project", "declare its meter",
217
+ "import these readings", "size a PV system for 80 % self-consumption".
218
+
219
+ ## Licence
220
+
221
+ [AGPL-3.0-only](../../LICENSE).
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `npx @nexgen-os/mcp`, over stdio — or `--http`, the same server by URL.
4
+ *
5
+ * Everything comes from the environment, because that is how an MCP client
6
+ * launches a server: a command and a block of variables. Nothing is read
7
+ * from a file and nothing is written to one. stdout belongs to the protocol;
8
+ * anything for a human goes to stderr.
9
+ */
10
+ import { createServer } from 'node:http';
11
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
12
+ import { connect } from '@nexgen-os/core';
13
+ import { ENV, refuseServiceRole } from './config.js';
14
+ import { handleNodeRequest } from './http.js';
15
+ import { SERVER_VERSION } from './server.js';
16
+ import { serverFromEnvironment } from './start.js';
17
+ const HELP = `nexgen-mcp — the Model Context Protocol server for Nexgen OS.
18
+
19
+ Over stdio (the default), started by a client with, in its "env" block:
20
+
21
+ ${ENV.dbUrl} the connection string of the database
22
+ and one person to act as:
23
+ ${ENV.apiKey} a key an owner issued (nexgen-os key create)
24
+ ${ENV.accessToken} a person's session, verified with ${ENV.supabaseUrl} and ${ENV.anonKey}
25
+ ${ENV.actAsUserId} the auth.users id of a person (self-hosted)
26
+ ${ENV.write}=1 lets the agent write; it reads otherwise
27
+
28
+ Over HTTP, for others to reach by URL:
29
+
30
+ nexgen-mcp --http [--port 8787]
31
+ with ${ENV.dbUrl}, ${ENV.supabaseUrl}, ${ENV.anonKey} and NEXGEN_MCP_ORIGIN (https://mcp.example.org)
32
+
33
+ Row level security applies either way. This server has no privileges of its
34
+ own and refuses a service_role key.
35
+ `;
36
+ async function serveHttp(port) {
37
+ refuseServiceRole(process.env);
38
+ const need = (name) => {
39
+ const value = process.env[name]?.trim();
40
+ if (!value)
41
+ throw new Error(`missing_configuration: --http needs ${name}`);
42
+ return value;
43
+ };
44
+ const dbUrl = need(ENV.dbUrl);
45
+ const options = {
46
+ origin: need('NEXGEN_MCP_ORIGIN'),
47
+ supabaseUrl: need(ENV.supabaseUrl),
48
+ anonKey: need(ENV.anonKey),
49
+ connect: () => connect(dbUrl),
50
+ };
51
+ createServer((req, res) => {
52
+ handleNodeRequest(req, res, options).catch((error) => {
53
+ res.statusCode = 500;
54
+ res.end(error instanceof Error ? error.message : String(error));
55
+ });
56
+ }).listen(port, () => process.stderr.write(`nexgen-mcp: Streamable HTTP on port ${port}, endpoint ${options.origin}/mcp\n`));
57
+ }
58
+ async function main() {
59
+ const args = process.argv.slice(2);
60
+ if (args.includes('--help') || args.includes('-h'))
61
+ return void process.stderr.write(HELP);
62
+ if (args.includes('--version') || args.includes('-v'))
63
+ return void process.stderr.write(`${SERVER_VERSION}\n`);
64
+ if (args.includes('--http')) {
65
+ const at = args.indexOf('--port');
66
+ return serveHttp(at === -1 ? 8787 : Number(args[at + 1]));
67
+ }
68
+ const { server, session, summary } = await serverFromEnvironment(process.env);
69
+ const shutdown = async () => {
70
+ await server.close().catch(() => { });
71
+ await session.close().catch(() => { });
72
+ process.exit(0);
73
+ };
74
+ process.on('SIGINT', () => void shutdown());
75
+ process.on('SIGTERM', () => void shutdown());
76
+ await server.connect(new StdioServerTransport());
77
+ process.stderr.write(`${summary}\n`);
78
+ }
79
+ main().catch((error) => {
80
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
81
+ process.exitCode = 1;
82
+ });
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Where the server gets its connection and who it acts as, and what it
3
+ * refuses: the rules of every surface (`@nexgen-os/core`, `surface.ts`),
4
+ * spoken as "this server".
5
+ */
6
+ import { type SurfaceConfig } from '@nexgen-os/core';
7
+ export { scopesOf, verifyAccessToken } from '@nexgen-os/core';
8
+ export declare const ENV: {
9
+ readonly supabaseUrl: "SUPABASE_URL";
10
+ readonly anonKey: "SUPABASE_ANON_KEY";
11
+ readonly dbUrl: "NEXGEN_DB_URL";
12
+ readonly apiKey: "NEXGEN_API_KEY";
13
+ readonly accessToken: "NEXGEN_ACCESS_TOKEN";
14
+ readonly actAsUserId: "NEXGEN_ACT_AS_USER_ID";
15
+ readonly write: "NEXGEN_WRITE";
16
+ };
17
+ export type Config = SurfaceConfig;
18
+ /** Refuses a `service_role` key wherever it was put, before anything connects. */
19
+ export declare const refuseServiceRole: (env: NodeJS.ProcessEnv) => void;
20
+ /** Reads the environment, and says what is missing rather than failing later. */
21
+ export declare const readConfig: (env?: NodeJS.ProcessEnv) => Config;
package/dist/config.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Where the server gets its connection and who it acts as, and what it
3
+ * refuses: the rules of every surface (`@nexgen-os/core`, `surface.ts`),
4
+ * spoken as "this server".
5
+ */
6
+ import { IDENTITY_ENV, readSurfaceConfig, refuseServiceRole as refuse } from '@nexgen-os/core';
7
+ export { scopesOf, verifyAccessToken } from '@nexgen-os/core';
8
+ export const ENV = IDENTITY_ENV;
9
+ const SURFACE = 'this server';
10
+ /** Refuses a `service_role` key wherever it was put, before anything connects. */
11
+ export const refuseServiceRole = (env) => refuse(env, SURFACE);
12
+ /** Reads the environment, and says what is missing rather than failing later. */
13
+ export const readConfig = (env = process.env) => readSurfaceConfig(env, SURFACE);
package/dist/http.d.ts ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The same server over HTTP: the Streamable HTTP transport of MCP,
3
+ * stateless, with the OAuth discovery a remote client follows — as Ekwo OS's
4
+ * hosted server answers it.
5
+ *
6
+ * `bin.ts` is a process a client starts on its own machine, and it reads who
7
+ * it acts as from its environment. A server reached by URL answers many
8
+ * people, so **who a request acts as is decided per request**, from the
9
+ * bearer it carries:
10
+ *
11
+ * - a key of Nexgen OS (`ngk_…`), presented to the database by
12
+ * `use_api_key()`: its issuer, within its organisation, read only unless
13
+ * it carries `write`;
14
+ * - a person's access token, verified by the installation's Supabase Auth,
15
+ * writing only when the person granted the scope `energy.write`.
16
+ *
17
+ * A request without one is answered `401` with a `WWW-Authenticate` header
18
+ * naming the protected-resource metadata (RFC 9728). The client follows it
19
+ * to the authorization server (RFC 8414) — by default the installation's own
20
+ * Supabase Auth, its OAuth 2.1 server — registers itself there (RFC 7591)
21
+ * and sends the person to approve the connection and choose whether the
22
+ * agent may write. This file serves the first document, and the second when
23
+ * the host is its own authorization server; it issues no token.
24
+ *
25
+ * Each request builds a server, answers in JSON and closes it: no session
26
+ * id, nothing kept, so it runs on a function platform, behind a load
27
+ * balancer, or in one process. A `GET` on the endpoint is `405`: this server
28
+ * never speaks first.
29
+ */
30
+ import type { IncomingMessage, ServerResponse } from 'node:http';
31
+ import { type Computations, type Geocoder, type SqlClient } from '@nexgen-os/core';
32
+ /** The scope an agent asks for to read, and the one that lets it write. */
33
+ export declare const SCOPES: {
34
+ readonly read: "energy";
35
+ readonly write: "energy.write";
36
+ };
37
+ export declare const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
38
+ export declare const AUTHORIZATION_SERVER_PATH = "/.well-known/oauth-authorization-server";
39
+ export interface HttpOptions {
40
+ /** Where this server is reached, `https://mcp.example.org`; the endpoint is `<origin>/mcp`. */
41
+ origin: string;
42
+ /** The installation's project, `https://<ref>.supabase.co`, whose Auth verifies sessions. */
43
+ supabaseUrl: string;
44
+ /** Its publishable (anon) key. Never the `service_role` key. */
45
+ anonKey: string;
46
+ /** A new connection to the database, for one request; closed when it is answered. */
47
+ connect: () => Promise<SqlClient>;
48
+ /** The authorization servers named in the metadata. Default: the installation's Supabase Auth. */
49
+ authorizationServers?: string[];
50
+ /** The RFC 8414 metadata of the host, when the host is its own authorization server (`authorizationServerMetadata()`). */
51
+ authorizationServer?: AuthorizationServerMetadata;
52
+ computations?: Computations;
53
+ geocoder?: Geocoder;
54
+ fetch?: typeof globalThis.fetch;
55
+ }
56
+ /** RFC 9728: what this resource is, and who authorizes access to it. */
57
+ export declare function protectedResourceMetadata(options: Pick<HttpOptions, 'origin' | 'supabaseUrl' | 'authorizationServers'>): {
58
+ resource: string;
59
+ authorization_servers: string[];
60
+ scopes_supported: ("energy" | "energy.write")[];
61
+ bearer_methods_supported: string[];
62
+ resource_name: string;
63
+ resource_documentation: string;
64
+ };
65
+ export interface AuthorizationServerMetadata {
66
+ issuer: string;
67
+ authorization_endpoint: string;
68
+ token_endpoint: string;
69
+ registration_endpoint: string;
70
+ scopes_supported: string[];
71
+ response_types_supported: string[];
72
+ grant_types_supported: string[];
73
+ code_challenge_methods_supported: string[];
74
+ token_endpoint_auth_methods_supported: string[];
75
+ revocation_endpoint?: string;
76
+ }
77
+ /**
78
+ * RFC 8414, for a host that is its own authorization server: the code flow
79
+ * with PKCE (S256) the MCP specification requires, public clients, and the
80
+ * dynamic registration endpoint of RFC 7591 so that a client needs no
81
+ * credentials of its own.
82
+ */
83
+ export declare function authorizationServerMetadata(issuer: string, endpoints: {
84
+ authorize: string;
85
+ token: string;
86
+ register: string;
87
+ revoke?: string;
88
+ }): AuthorizationServerMetadata;
89
+ /** Answers one HTTP request: the discovery documents, or the MCP endpoint. */
90
+ export declare function handleHttpRequest(request: Request, options: HttpOptions): Promise<Response>;
91
+ /** The same handler for `node:http`: the request read into a web `Request`, the `Response` written back. */
92
+ export declare function handleNodeRequest(req: IncomingMessage, res: ServerResponse, options: HttpOptions): Promise<void>;
package/dist/http.js ADDED
@@ -0,0 +1,148 @@
1
+ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
2
+ import { installedModules, isServiceRoleKey, personSession, serviceRoleRefusal, } from '@nexgen-os/core';
3
+ import { scopesOf, verifyAccessToken } from './config.js';
4
+ import { buildServer } from './server.js';
5
+ /** The scope an agent asks for to read, and the one that lets it write. */
6
+ export const SCOPES = { read: 'energy', write: 'energy.write' };
7
+ export const PROTECTED_RESOURCE_PATH = '/.well-known/oauth-protected-resource';
8
+ export const AUTHORIZATION_SERVER_PATH = '/.well-known/oauth-authorization-server';
9
+ /** RFC 9728: what this resource is, and who authorizes access to it. */
10
+ export function protectedResourceMetadata(options) {
11
+ const origin = options.origin.replace(/\/+$/, '');
12
+ return {
13
+ resource: `${origin}/mcp`,
14
+ authorization_servers: options.authorizationServers ?? [`${options.supabaseUrl.replace(/\/+$/, '')}/auth/v1`],
15
+ scopes_supported: [SCOPES.read, SCOPES.write],
16
+ bearer_methods_supported: ['header'],
17
+ resource_name: 'Nexgen OS',
18
+ resource_documentation: 'https://github.com/nexgen-os/nexgen-os/tree/main/packages/mcp#readme',
19
+ };
20
+ }
21
+ /**
22
+ * RFC 8414, for a host that is its own authorization server: the code flow
23
+ * with PKCE (S256) the MCP specification requires, public clients, and the
24
+ * dynamic registration endpoint of RFC 7591 so that a client needs no
25
+ * credentials of its own.
26
+ */
27
+ export function authorizationServerMetadata(issuer, endpoints) {
28
+ const base = issuer.replace(/\/+$/, '');
29
+ const at = (path) => new URL(path, `${base}/`).toString();
30
+ return {
31
+ issuer: base,
32
+ authorization_endpoint: at(endpoints.authorize),
33
+ token_endpoint: at(endpoints.token),
34
+ registration_endpoint: at(endpoints.register),
35
+ ...(endpoints.revoke ? { revocation_endpoint: at(endpoints.revoke) } : {}),
36
+ scopes_supported: [SCOPES.read, SCOPES.write],
37
+ response_types_supported: ['code'],
38
+ grant_types_supported: ['authorization_code', 'refresh_token'],
39
+ code_challenge_methods_supported: ['S256'],
40
+ token_endpoint_auth_methods_supported: ['none'],
41
+ };
42
+ }
43
+ const json = (status, body, headers = {}) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...headers } });
44
+ const rpcError = (status, code, message, headers = {}) => json(status, { jsonrpc: '2.0', error: { code, message }, id: null }, headers);
45
+ /** The challenge of RFC 9728 §5.1: where the client learns how to get a token. */
46
+ function unauthorized(options, error) {
47
+ const metadata = `${options.origin.replace(/\/+$/, '')}${PROTECTED_RESOURCE_PATH}`;
48
+ const challenge = `Bearer resource_metadata="${metadata}", scope="${SCOPES.read}"${error ? `, error="${error}"` : ''}`;
49
+ return rpcError(401, -32001, error === undefined
50
+ ? 'unauthorized: connect with a person\'s session or a key of Nexgen OS; the WWW-Authenticate header says where to get one.'
51
+ : `${error}: the bearer was not recognised by this installation.`, { 'WWW-Authenticate': challenge });
52
+ }
53
+ /** The session a bearer acts as, or the response that refuses it. */
54
+ async function sessionFor(request, options) {
55
+ const header = request.headers.get('authorization') ?? '';
56
+ const bearer = /^Bearer\s+(.+)$/i.exec(header)?.[1]?.trim();
57
+ if (bearer === undefined || bearer.length === 0)
58
+ return unauthorized(options);
59
+ if (isServiceRoleKey(bearer)) {
60
+ return rpcError(403, -32001, serviceRoleRefusal('the bearer of the request', 'authorization', 'this server', 'connect with a person\'s session or a key of Nexgen OS'));
61
+ }
62
+ if (bearer.startsWith('ngk_')) {
63
+ // The database checks the key at the top of every transaction; a key
64
+ // without write runs read only, whatever this says.
65
+ return personSession(await options.connect(), { kind: 'key', secret: bearer }, { writable: true });
66
+ }
67
+ let userId;
68
+ try {
69
+ ({ userId } = await verifyAccessToken(options.supabaseUrl, options.anonKey, bearer, options.fetch));
70
+ }
71
+ catch {
72
+ return unauthorized(options, 'invalid_token');
73
+ }
74
+ return personSession(await options.connect(), { kind: 'user', userId }, { writable: scopesOf(bearer).includes(SCOPES.write) });
75
+ }
76
+ /** Answers one HTTP request: the discovery documents, or the MCP endpoint. */
77
+ export async function handleHttpRequest(request, options) {
78
+ if (isServiceRoleKey(options.anonKey)) {
79
+ return rpcError(500, -32001, serviceRoleRefusal('the publishable key of this server', 'apikey', 'this server', 'configure the anon (publishable) key'));
80
+ }
81
+ const path = new URL(request.url).pathname.replace(/\/+$/, '');
82
+ if (request.method === 'GET' && (path === PROTECTED_RESOURCE_PATH || path === `${PROTECTED_RESOURCE_PATH}/mcp`)) {
83
+ return json(200, protectedResourceMetadata(options));
84
+ }
85
+ if (request.method === 'GET' && path === AUTHORIZATION_SERVER_PATH) {
86
+ return options.authorizationServer === undefined ? json(404, { error: 'not_found' }) : json(200, options.authorizationServer);
87
+ }
88
+ if (path !== '/mcp')
89
+ return json(404, { error: 'not_found' });
90
+ if (request.method !== 'POST')
91
+ return new Response(null, { status: 405, headers: { Allow: 'POST' } });
92
+ let body;
93
+ try {
94
+ body = await request.json();
95
+ }
96
+ catch {
97
+ return rpcError(400, -32700, 'Parse error: the body is not JSON.');
98
+ }
99
+ let session;
100
+ try {
101
+ session = await sessionFor(request, options);
102
+ }
103
+ catch (error) {
104
+ return rpcError(200, -32001, error instanceof Error ? error.message : String(error));
105
+ }
106
+ if (session instanceof Response)
107
+ return session;
108
+ try {
109
+ const modules = await session.run(installedModules).catch(() => []);
110
+ const server = buildServer(session, {
111
+ modules,
112
+ ...(options.computations ? { computations: options.computations } : {}),
113
+ ...(options.geocoder ? { geocoder: options.geocoder } : {}),
114
+ });
115
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
116
+ try {
117
+ await server.connect(transport);
118
+ return await transport.handleRequest(request, { parsedBody: body });
119
+ }
120
+ finally {
121
+ await server.close().catch(() => { });
122
+ }
123
+ }
124
+ finally {
125
+ await session.close().catch(() => { });
126
+ }
127
+ }
128
+ /** The same handler for `node:http`: the request read into a web `Request`, the `Response` written back. */
129
+ export async function handleNodeRequest(req, res, options) {
130
+ const chunks = [];
131
+ for await (const chunk of req)
132
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
133
+ const headers = new Headers();
134
+ for (const [name, value] of Object.entries(req.headers)) {
135
+ if (value !== undefined)
136
+ headers.set(name, Array.isArray(value) ? value.join(', ') : value);
137
+ }
138
+ const method = req.method ?? 'GET';
139
+ const request = new Request(new URL(req.url ?? '/', options.origin), {
140
+ method,
141
+ headers,
142
+ ...(method === 'GET' || method === 'HEAD' ? {} : { body: Buffer.concat(chunks) }),
143
+ });
144
+ const response = await handleHttpRequest(request, options);
145
+ res.statusCode = response.status;
146
+ response.headers.forEach((value, name) => res.setHeader(name, value));
147
+ res.end(Buffer.from(await response.arrayBuffer()));
148
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The server as a library: for the tests, which call it against a real
3
+ * schema, and for a host that mounts it on a transport of its own.
4
+ */
5
+ export { ENV, readConfig, refuseServiceRole, scopesOf, verifyAccessToken, type Config } from './config.js';
6
+ export { AUTHORIZATION_SERVER_PATH, PROTECTED_RESOURCE_PATH, SCOPES, authorizationServerMetadata, handleHttpRequest, handleNodeRequest, protectedResourceMetadata, type AuthorizationServerMetadata, type HttpOptions, } from './http.js';
7
+ export { ALL_TOOLS, INSTRUCTIONS, SERVER_NAME, SERVER_VERSION, buildServer, instructionsFor, type ServerOptions } from './server.js';
8
+ export { SCHEMA_MIN } from './schema.js';
9
+ export { openSession, serverFromEnvironment, type StartOptions, type Started } from './start.js';
10
+ export { isMissingConfiguration, unconfiguredSession } from './unconfigured.js';
11
+ export { MODULE_TOOLS, moduleToolsFor } from './tools/modules.js';
12
+ export { READ_TOOLS } from './tools/read.js';
13
+ export { WRITE_TOOLS } from './tools/write.js';
14
+ export type { Tool, ToolContext } from './tools/tool.js';
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The server as a library: for the tests, which call it against a real
3
+ * schema, and for a host that mounts it on a transport of its own.
4
+ */
5
+ export { ENV, readConfig, refuseServiceRole, scopesOf, verifyAccessToken } from './config.js';
6
+ export { AUTHORIZATION_SERVER_PATH, PROTECTED_RESOURCE_PATH, SCOPES, authorizationServerMetadata, handleHttpRequest, handleNodeRequest, protectedResourceMetadata, } from './http.js';
7
+ export { ALL_TOOLS, INSTRUCTIONS, SERVER_NAME, SERVER_VERSION, buildServer, instructionsFor } from './server.js';
8
+ export { SCHEMA_MIN } from './schema.js';
9
+ export { openSession, serverFromEnvironment } from './start.js';
10
+ export { isMissingConfiguration, unconfiguredSession } from './unconfigured.js';
11
+ export { MODULE_TOOLS, moduleToolsFor } from './tools/modules.js';
12
+ export { READ_TOOLS } from './tools/read.js';
13
+ export { WRITE_TOOLS } from './tools/write.js';
@@ -0,0 +1,2 @@
1
+ /** The oldest schema this server speaks to, as `package.json` declares it under `nexgenOs.schemaMin`; a test keeps them equal. */
2
+ export declare const SCHEMA_MIN = "0.4.0";
package/dist/schema.js ADDED
@@ -0,0 +1,2 @@
1
+ /** The oldest schema this server speaks to, as `package.json` declares it under `nexgenOs.schemaMin`; a test keeps them equal. */
2
+ export const SCHEMA_MIN = '0.4.0';
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The server itself: the tools of the core, the tools of the modules
3
+ * installed, and the instructions of the handshake.
4
+ *
5
+ * The descriptions are written for a model: when to reach for the tool,
6
+ * what comes back, and what it will not do. Every call runs in one
7
+ * transaction acting as the person (`Session`), and a refusal comes back
8
+ * with the database's own name first and a sentence on what to do next.
9
+ */
10
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
11
+ import { type Computations, type Geocoder, type Session } from '@nexgen-os/core';
12
+ import type { Tool } from './tools/tool.js';
13
+ export declare const SERVER_NAME = "@nexgen-os/mcp";
14
+ /** Repeated from `package.json`, so that a bundle without a manifest still says what it is; a test keeps them equal. */
15
+ export declare const SERVER_VERSION = "0.4.1";
16
+ export declare const INSTRUCTIONS: string;
17
+ export interface ServerOptions {
18
+ /** The modules installed on the database; their tools are offered. None: the core's tools only. */
19
+ modules?: readonly string[];
20
+ /** The computations of the modules that are code (`solar.size`, `solar.yield`, `battery.size`, `community.settle`, `charging.size`). */
21
+ computations?: Computations;
22
+ /** The geocoder chain the person configured (`geocoderFor()`). None: an address is refused, a place is not. */
23
+ geocoder?: Geocoder;
24
+ }
25
+ /** Every tool this server can offer, the modules' included: what `list_modules` and the README name. */
26
+ export declare const ALL_TOOLS: Tool[];
27
+ export declare function instructionsFor(session: Pick<Session, 'writable'> | undefined): string;
28
+ export declare function buildServer(session: Session, options?: ServerOptions): McpServer;