@nexgen-os/mcp 0.0.0-stage → 0.4.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/dist/server.js ADDED
@@ -0,0 +1,83 @@
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 { GestureError, explain, status } from '@nexgen-os/core';
12
+ import { z } from 'zod';
13
+ import { READ_TOOLS } from './tools/read.js';
14
+ import { MODULE_TOOLS, moduleToolsFor } from './tools/modules.js';
15
+ import { WRITE_TOOLS } from './tools/write.js';
16
+ export const SERVER_NAME = '@nexgen-os/mcp';
17
+ /** Repeated from `package.json`, so that a bundle without a manifest still says what it is; a test keeps them equal. */
18
+ export const SERVER_VERSION = '0.4.0';
19
+ export const INSTRUCTIONS = [
20
+ 'Nexgen OS is a world model for energy assets in the person\'s own Postgres: organisations, projects, participants, their meters, devices and series. You act as that person: what you see and change is what row level security lets them see and change. There is no agent role and no back door. Dates are ISO, identifiers uuids, a value is dated at the start of its interval, an azimuth in degrees clockwise from true north.',
21
+ 'A first session. (1) status, then list_organisations and list_projects: everything belongs to an organisation. (2) list_participants: a participant without a time zone has no daily readings; say so. (3) Describe with a source: add_participant with its place, declare_meter, install_device, store_series or import_series. (4) Compute as a module does: solar_estimate_yield, solar_size, battery_size and charging_size with a criterion the person chose, community_settle, kpis_compute; read back with read_series, solar_estimates, kpis_of. (5) Show what you attached and what the estimate read, then propose with actions_propose; the person validates.',
22
+ 'Never compute a figure yourself and write it as if a module had; never assume a country, a currency, a language or a time zone; never send the data anywhere the person did not configure.',
23
+ 'When the database refuses, the message starts with a name — time_zone_required, read_only, not_allowed, api_key_revoked — followed by a sentence saying what to do. Report it to the person; do not retry blindly or work around it.',
24
+ ].join('\n\n');
25
+ function ok(payload) {
26
+ return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
27
+ }
28
+ /** A refusal, with the database's own words first and what to do underneath. */
29
+ function fail(error) {
30
+ const e = explain(error);
31
+ return { isError: true, content: [{ type: 'text', text: e.hint === undefined ? e.message : `${e.message}\n\n${e.hint}` }] };
32
+ }
33
+ /** Every tool this server can offer, the modules' included: what `list_modules` and the README name. */
34
+ export const ALL_TOOLS = [...READ_TOOLS, ...WRITE_TOOLS, ...MODULE_TOOLS];
35
+ export function instructionsFor(session) {
36
+ const writing = session?.writable === false
37
+ ? 'This connection READS: every write is refused as read_only. The person allows writing (NEXGEN_WRITE=1, a key with write, or the scope energy.write); say so when a write is asked for.'
38
+ : 'This connection may write, as the person — unless it is a key issued without write, which the database runs read only (read_only). Show what you are about to write before you write it.';
39
+ return `${INSTRUCTIONS}\n\n${writing}`;
40
+ }
41
+ export function buildServer(session, options = {}) {
42
+ const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: instructionsFor(session) });
43
+ const modules = options.modules ?? [];
44
+ const tools = [...READ_TOOLS, ...WRITE_TOOLS, ...moduleToolsFor(modules)];
45
+ const register = (t) => {
46
+ server.registerTool(t.name, {
47
+ title: t.title,
48
+ description: t.description,
49
+ inputSchema: t.input.shape,
50
+ annotations: {
51
+ title: t.title,
52
+ readOnlyHint: !t.writes,
53
+ destructiveHint: t.destructive === true,
54
+ openWorldHint: t.name === 'solar_estimate_yield' || t.name === 'add_participant',
55
+ },
56
+ }, async (args) => {
57
+ try {
58
+ const parsed = t.input.parse(args ?? {});
59
+ return ok(await session.run((db) => t.run({ db, computations: options.computations ?? {}, geocoder: options.geocoder }, parsed)));
60
+ }
61
+ catch (error) {
62
+ return fail(error instanceof z.ZodError ? new GestureError(`invalid_arguments: ${error.message}`) : error);
63
+ }
64
+ });
65
+ };
66
+ for (const t of tools)
67
+ register(t);
68
+ server.registerTool('list_modules', {
69
+ title: 'Modules and their tools',
70
+ description: 'The modules installed on this database, each with the tools it adds here. A module that is not installed offers none: nexgen-os init --modules adds it.',
71
+ inputSchema: {},
72
+ annotations: { title: 'Modules and their tools', readOnlyHint: true, openWorldHint: false },
73
+ }, async () => {
74
+ try {
75
+ const installed = (await session.run(status)).modules;
76
+ return ok(installed.map((m) => ({ ...m, tools: MODULE_TOOLS.filter((t) => t.module === m.code).map((t) => t.name) })));
77
+ }
78
+ catch (error) {
79
+ return fail(error);
80
+ }
81
+ });
82
+ return server;
83
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * From an environment to a server, without the transport.
3
+ *
4
+ * `bin.ts` connects the result to stdio; the tests connect it to an
5
+ * in-memory client. With nothing configured the server still starts and
6
+ * offers the core's tools, and every call says what to set — only absence
7
+ * is forgiven: a `service_role` key, two people to act as or a malformed id
8
+ * are refused at start (`unconfigured.ts`).
9
+ */
10
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
11
+ import { type Computations, type Geocoder, type Session } from '@nexgen-os/core';
12
+ import { type Config } from './config.js';
13
+ export interface Started {
14
+ server: McpServer;
15
+ session: Session;
16
+ /** One line for stderr: how this server is connected, or why it is not. */
17
+ summary: string;
18
+ }
19
+ export interface StartOptions {
20
+ computations?: Computations;
21
+ geocoder?: Geocoder;
22
+ fetch?: typeof globalThis.fetch;
23
+ }
24
+ /** The session a configuration describes. The caller closes it. */
25
+ export declare const openSession: (config: Config, options?: {
26
+ fetch?: typeof globalThis.fetch;
27
+ }) => Promise<Session>;
28
+ export declare function serverFromEnvironment(env?: NodeJS.ProcessEnv, options?: StartOptions): Promise<Started>;
package/dist/start.js ADDED
@@ -0,0 +1,34 @@
1
+ import { geocoderChain, geocoderNames, installedModules, loadGeocoders, nexgenSchemaFloor, openPersonSession } from '@nexgen-os/core';
2
+ import { readConfig } from './config.js';
3
+ import { buildServer } from './server.js';
4
+ import { isMissingConfiguration, unconfiguredSession } from './unconfigured.js';
5
+ import { SCHEMA_MIN } from './schema.js';
6
+ /** The session a configuration describes. The caller closes it. */
7
+ export const openSession = (config, options = {}) => openPersonSession(config, options);
8
+ export async function serverFromEnvironment(env = process.env, options = {}) {
9
+ let config;
10
+ try {
11
+ config = readConfig(env);
12
+ }
13
+ catch (error) {
14
+ if (!isMissingConfiguration(error))
15
+ throw error;
16
+ const session = unconfiguredSession(error);
17
+ return {
18
+ server: buildServer(session),
19
+ session,
20
+ summary: `nexgen-mcp: started without a database — every tool will answer with what to configure. ${error.message}`,
21
+ };
22
+ }
23
+ const session = await openSession(config, options);
24
+ const version = await session.run((db) => nexgenSchemaFloor(db, SCHEMA_MIN));
25
+ const modules = await session.run(installedModules);
26
+ // The geocoders the person named, keyed by the places their sources serve.
27
+ const geocoder = options.geocoder
28
+ ?? await session.run(async (db) => geocoderChain(db, await loadGeocoders(geocoderNames(env), env)));
29
+ return {
30
+ server: buildServer(session, { modules, ...(options.computations ? { computations: options.computations } : {}), ...(geocoder ? { geocoder } : {}) }),
31
+ session,
32
+ summary: `nexgen-mcp: connected as ${session.actingAs}, ${session.writable ? 'reading and writing' : 'reading only'}, schema ${version}${modules.length ? `, modules: ${modules.join(', ')}` : ''}`,
33
+ };
34
+ }
@@ -0,0 +1,4 @@
1
+ import { type Tool } from './tool.js';
2
+ export declare const MODULE_TOOLS: Tool[];
3
+ /** The tools of the modules installed, in the order above. */
4
+ export declare function moduleToolsFor(installed: readonly string[]): Tool[];
@@ -0,0 +1,210 @@
1
+ /**
2
+ * The tools of the modules: offered when the module is installed on the
3
+ * database (`modules`), under its code as a prefix, as Ekwo OS offers its
4
+ * modules' tools. A figure comes from the module that computes it, kept in
5
+ * the table named after what it gives, with its provenance; these tools
6
+ * call the module and read back what it kept.
7
+ */
8
+ import * as core from '@nexgen-os/core';
9
+ import { z } from 'zod';
10
+ import { tool } from './tool.js';
11
+ const uuid = z.string().uuid();
12
+ const instant = z.string().describe('An ISO 8601 instant');
13
+ const objectKind = z.enum(['participant', 'project', 'meter', 'device']);
14
+ const engineName = z.string().regex(/^[a-z0-9_-]+$/)
15
+ .describe('The name of the engine; its command is the one the person configured (NEXGEN_ENGINE_<NAME>), never one given here');
16
+ const economics = z.object({
17
+ offtakePricePerKwh: z.number(), injectionPricePerKwh: z.number(), costPerKwp: z.number(),
18
+ horizonYears: z.number().int().positive(), discountRate: z.number(), currency: z.string().length(3),
19
+ }).describe('The money of the person, in the currency of the place. Never assumed');
20
+ export const MODULE_TOOLS = [
21
+ // ------------------------------------------------------------------- kpis
22
+ tool({
23
+ name: 'kpis_of',
24
+ title: 'Indicators of an object',
25
+ module: 'kpis',
26
+ description: 'The indicators of a participant, a project, a meter or a device over a period (kpis.of()): each value with its unit, its target and whether it is met, and the figure it was kept as.',
27
+ input: z.object({ object_kind: objectKind, object_id: uuid, from: instant, to: instant }),
28
+ writes: false,
29
+ run: ({ db }, a) => core.kpisOf(db, a.object_kind, a.object_id, a.from, a.to),
30
+ }),
31
+ tool({
32
+ name: 'kpis_compute',
33
+ title: 'Compute an indicator',
34
+ module: 'kpis',
35
+ description: 'Computes one indicator of an object over a period and keeps it as a figure (kpis.compute()). Returns the figure id; kpis_of reads it back.',
36
+ input: z.object({ object_kind: objectKind, object_id: uuid, indicator: z.string(), from: instant, to: instant }),
37
+ writes: true,
38
+ run: ({ db }, a) => core.computeKpi(db, a.object_kind, a.object_id, a.indicator, a.from, a.to),
39
+ }),
40
+ // ------------------------------------------------------------------ solar
41
+ tool({
42
+ name: 'solar_estimates',
43
+ title: 'PV estimates',
44
+ module: 'solar',
45
+ description: 'The estimates of the solar module about a participant or a PV system — yields and sizings — with their inputs, their provenance and their results, latest first.',
46
+ input: z.object({ participant_id: uuid.optional(), device_id: uuid.optional(), kind: z.string().optional() }),
47
+ writes: false,
48
+ run: ({ db }, a) => core.estimatesOf(db, 'solar', a),
49
+ }),
50
+ tool({
51
+ name: 'solar_size',
52
+ title: 'Size a PV system',
53
+ module: 'solar',
54
+ description: 'The PV power that best meets a named criterion for a participant (solar.size(), decision 0045), within the limit of its roof or a stated maximum. The criterion is a code of sizing_criteria the person chose — never assume one. Keeps a sizing estimate and returns it.',
55
+ input: z.object({
56
+ participantId: uuid, criterion: z.string(), target: z.number().min(0).max(1).optional(),
57
+ from: instant, to: instant, step: z.string(),
58
+ shape: z.object({ seriesId: uuid, kwp: z.number().positive() }).describe('A production series and the power it was computed for'),
59
+ bounds: z.object({ maxKwp: z.number().positive().optional(), source: z.string().optional() }).optional(),
60
+ economics: economics.optional(),
61
+ }),
62
+ writes: true,
63
+ run: ({ db, computations }, a) => core.compute(db, computations, 'solar.size', a),
64
+ }),
65
+ tool({
66
+ name: 'solar_estimate_yield',
67
+ title: 'Estimate a PV yield',
68
+ module: 'solar',
69
+ description: 'The yield of a PV system over whole years, with a named profile (pvgis_like by default, pvwatts, or an engine), kept in solar.estimates with what it was computed from. It reaches PVGIS on the Internet unless the profile computes here.',
70
+ input: z.object({
71
+ deviceId: uuid, years: z.object({ from: z.number().int(), to: z.number().int() }), profileCode: z.string().optional(),
72
+ raddatabase: z.string().optional(), typicalYear: z.boolean().optional(), anchor: z.enum(['pvgis', 'none']).optional(),
73
+ engine: z.object({ name: engineName }).optional(), replaces: uuid.optional(),
74
+ }),
75
+ writes: true,
76
+ run: ({ db, computations }, a) => core.compute(db, computations, 'solar.yield', a),
77
+ }),
78
+ // ---------------------------------------------------------------- battery
79
+ tool({
80
+ name: 'battery_estimates',
81
+ title: 'Battery estimates',
82
+ module: 'battery',
83
+ description: 'The estimates of the battery module about a participant or a battery — dispatches and sizings — with their inputs, provenance and results, latest first.',
84
+ input: z.object({ participant_id: uuid.optional(), device_id: uuid.optional(), kind: z.string().optional() }),
85
+ writes: false,
86
+ run: ({ db }, a) => core.estimatesOf(db, 'battery', a),
87
+ }),
88
+ tool({
89
+ name: 'battery_size',
90
+ title: 'Size a battery',
91
+ module: 'battery',
92
+ description: 'The battery capacity that best meets a named criterion for a participant or a project (battery.size(), decision 0045), over a period, sweeping the capacities of the bounds. The criterion is the person\'s. Keeps a sizing estimate and returns it.',
93
+ input: z.object({
94
+ perimeter: z.object({ kind: z.enum(['participant', 'project']), id: uuid }),
95
+ criterion: z.enum(['self_consumption_rate', 'self_sufficiency', 'payback', 'net_present_value', 'max_power']),
96
+ from: instant, to: instant, step: z.string().optional(),
97
+ bounds: z.object({ minKwh: z.number().optional(), maxKwh: z.number().optional(), stepKwh: z.number().optional(), points: z.number().int().optional() }).optional(),
98
+ }),
99
+ writes: true,
100
+ run: ({ db, computations }, a) => core.compute(db, computations, 'battery.size', a),
101
+ }),
102
+ // -------------------------------------------------------------- community
103
+ tool({
104
+ name: 'community_settlements',
105
+ title: 'Settlements of a sharing',
106
+ module: 'community',
107
+ description: 'The settlements of the energy shared within a project, latest first: who received what, step by step, and the engine that computed it.',
108
+ input: z.object({ project_id: uuid }),
109
+ writes: false,
110
+ run: ({ db }, a) => core.settlementsOf(db, a.project_id),
111
+ }),
112
+ tool({
113
+ name: 'community_settle',
114
+ title: 'Settle a sharing',
115
+ module: 'community',
116
+ description: 'Settles the energy shared within a project over a period, by the sharing engine the person configured, and keeps the settlement in community.settlements. The rules are what the pack of the country or the project sets.',
117
+ input: z.object({ projectId: uuid, from: instant, to: instant, step: z.string(), engine: z.object({ name: engineName }), replaces: uuid.optional() }),
118
+ writes: true,
119
+ run: ({ db, computations }, a) => core.compute(db, computations, 'community.settle', a),
120
+ }),
121
+ // --------------------------------------------------------------- charging
122
+ tool({
123
+ name: 'charging_sessions',
124
+ title: 'Charging sessions',
125
+ module: 'charging',
126
+ description: 'The charging sessions of a charger or of a participant\'s chargers, latest first: EVSE, start and end, energy delivered, peak power, why it stopped, where it comes from. The id token is personal data and is not returned.',
127
+ input: z.object({ device_id: uuid.optional(), participant_id: uuid.optional(), from: instant.optional(), to: instant.optional() }),
128
+ writes: false,
129
+ run: ({ db }, a) => core.chargingSessionsOf(db, a),
130
+ }),
131
+ tool({
132
+ name: 'charging_limit',
133
+ title: 'Limit a charger',
134
+ module: 'charging',
135
+ description: 'Asks a charger to keep a charging profile (charging.limit(), an OCPP SetChargingProfile): a command action, proposed by you, on the charger\'s setpoint series. Nothing is sent until the person validates it with actions_validate; the station\'s answer marks it done or failed.',
136
+ input: z.object({
137
+ device_id: uuid,
138
+ schedule: z.object({
139
+ evse_id: z.number().int().min(0).optional(),
140
+ purpose: z.enum(['station_max', 'tx_default', 'tx', 'external_constraints']).optional(),
141
+ stack_level: z.number().int().min(0).optional(),
142
+ kind: z.enum(['absolute', 'relative', 'recurring']).optional(),
143
+ recurrency: z.enum(['daily', 'weekly']).optional(),
144
+ rate_unit: z.enum(['W', 'A']),
145
+ starts_at: instant.optional(), duration_s: z.number().int().positive().optional(),
146
+ valid_from: instant.optional(), valid_to: instant.optional(), transaction_id: z.string().optional(),
147
+ periods: z.array(z.object({ start_s: z.number().min(0), limit: z.number().min(0), phases: z.number().int().min(1).max(3).optional() })).min(1),
148
+ }),
149
+ }),
150
+ writes: true,
151
+ run: ({ db }, a) => core.limitCharging(db, a.device_id, a.schedule),
152
+ }),
153
+ tool({
154
+ name: 'charging_size',
155
+ title: 'Size charge points',
156
+ module: 'charging',
157
+ description: 'The number of charge points and their power for a participant or a project (charging.size(), decision 0045), from the arrivals and departures of its vehicles as the person gives them, within the power of its connection. The criterion is the person\'s: demand_served with a target, or max_power. Keeps a sizing estimate and returns it.',
158
+ input: z.object({
159
+ subject: z.object({ kind: z.enum(['participant', 'project']), id: uuid }),
160
+ criterion: z.enum(['demand_served', 'max_power']),
161
+ target: z.number().min(0).max(1).optional(),
162
+ vehicles: z.array(z.object({
163
+ arrival: z.string().regex(/^\d{2}:\d{2}$/), departure: z.string().regex(/^\d{2}:\d{2}$/),
164
+ energyKwh: z.number().min(0), count: z.number().int().positive().optional(),
165
+ })).min(1),
166
+ bounds: z.object({
167
+ powersKw: z.array(z.number().positive()).min(1), maxPoints: z.number().int().positive().optional(),
168
+ connectionKw: z.number().positive().optional(), baseLoadKw: z.number().min(0).optional(),
169
+ }),
170
+ }),
171
+ writes: true,
172
+ run: ({ db, computations }, a) => core.compute(db, computations, 'charging.size', a),
173
+ }),
174
+ // ---------------------------------------------------------------- actions
175
+ tool({
176
+ name: 'actions_of_project',
177
+ title: 'Actions of a project',
178
+ module: 'actions',
179
+ description: 'What is to be done on a project and its participants: steps, recommendations and commands, each with its phase, its status and the estimate its gain rests on.',
180
+ input: z.object({ project_id: uuid }),
181
+ writes: false,
182
+ run: ({ db }, a) => core.actionsOf(db, a.project_id),
183
+ }),
184
+ tool({
185
+ name: 'actions_propose',
186
+ title: 'Propose an action',
187
+ module: 'actions',
188
+ description: 'What you recommend, as an action proposed by an agent (actions.propose(), source agent), resting on the estimate that gives its gain. The person validates it; you never do it for them.',
189
+ input: z.object({
190
+ object_kind: z.string(), object_id: uuid, phase: z.string(), name: z.string().min(1),
191
+ estimate_kind: z.string().optional(), estimate_id: uuid.optional(), gain_per_year: z.number().optional(), horizon_years: z.number().int().optional(),
192
+ }),
193
+ writes: true,
194
+ run: ({ db }, a) => core.proposeAction(db, a),
195
+ }),
196
+ tool({
197
+ name: 'actions_validate',
198
+ title: 'Validate an action',
199
+ module: 'actions',
200
+ description: 'Moves an action along its lifecycle (actions.move()): validated, launched, done, failed or dismissed. Only on the person\'s explicit word.',
201
+ input: z.object({ action_id: uuid, status: z.enum(['validated', 'launched', 'done', 'failed', 'dismissed']), on: z.string().optional() }),
202
+ writes: true,
203
+ destructive: true,
204
+ run: ({ db }, a) => core.moveAction(db, a.action_id, a.status, a.on),
205
+ }),
206
+ ];
207
+ /** The tools of the modules installed, in the order above. */
208
+ export function moduleToolsFor(installed) {
209
+ return MODULE_TOOLS.filter((t) => t.module !== undefined && installed.includes(t.module));
210
+ }
@@ -0,0 +1,2 @@
1
+ import { type Tool } from './tool.js';
2
+ export declare const READ_TOOLS: Tool[];
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Reading the model: who you are, the six objects, their series and their
3
+ * parameters. Nothing here writes.
4
+ */
5
+ import * as core from '@nexgen-os/core';
6
+ import { z } from 'zod';
7
+ import { tool } from './tool.js';
8
+ const uuid = z.string().uuid();
9
+ const instant = z.string().describe('An ISO 8601 instant, 2026-01-01T00:00:00Z');
10
+ const limit = z.number().int().min(1).max(1000).optional().describe('At most this many rows; 100 by default');
11
+ /** One list per object of the core, filtered by the columns its list takes. */
12
+ const lists = [
13
+ tool({
14
+ name: 'list_organisations',
15
+ title: 'List organisations',
16
+ description: 'The organisations you are a member of. Start here: a project, a participant and everything under them belong to one. Organisations you were never invited to are invisible, not hidden. Next: list_projects.',
17
+ input: z.object({ limit }),
18
+ writes: false,
19
+ run: ({ db }, a) => core.listObjects(db, 'organisation', {}, a.limit),
20
+ }),
21
+ tool({
22
+ name: 'list_projects',
23
+ title: 'List projects',
24
+ description: 'The projects of an organisation, or every project you can read: a rooftop PV project, an energy community, a study of sites. Each says its kind, the frame it is carried out in (null when none), and the country whose rules apply. Next: list_participants.',
25
+ input: z.object({ organisation_id: uuid.optional(), limit }),
26
+ writes: false,
27
+ run: ({ db }, a) => core.listObjects(db, 'project', { organisation_id: a.organisation_id }, a.limit),
28
+ }),
29
+ tool({
30
+ name: 'list_participants',
31
+ title: 'List participants',
32
+ description: 'The participants of a project: a household, a school, a company, each with its place, its municipality, its time zone and how precisely it was located. A participant without a time zone has no daily readings; say so. Next: list_meters and list_devices.',
33
+ input: z.object({ project_id: uuid.optional(), organisation_id: uuid.optional(), limit }),
34
+ writes: false,
35
+ run: ({ db }, a) => core.listObjects(db, 'participant', { project_id: a.project_id, organisation_id: a.organisation_id }, a.limit),
36
+ }),
37
+ tool({
38
+ name: 'list_meters',
39
+ title: 'List meters',
40
+ description: 'The meters of a participant: an identifier in its scheme, the resource, the direction. A meter measures offtake and injection, never production.',
41
+ input: z.object({ participant_id: uuid.optional(), organisation_id: uuid.optional(), limit }),
42
+ writes: false,
43
+ run: ({ db }, a) => core.listObjects(db, 'meter', { participant_id: a.participant_id, organisation_id: a.organisation_id }, a.limit),
44
+ }),
45
+ tool({
46
+ name: 'list_devices',
47
+ title: 'List devices',
48
+ description: 'The devices of a participant: a PV system, a battery, a heat pump, a charging point, each with its type, its product and its rated power.',
49
+ input: z.object({ participant_id: uuid.optional(), organisation_id: uuid.optional(), limit }),
50
+ writes: false,
51
+ run: ({ db }, a) => core.listObjects(db, 'device', { participant_id: a.participant_id, organisation_id: a.organisation_id }, a.limit),
52
+ }),
53
+ tool({
54
+ name: 'list_series',
55
+ title: 'List series',
56
+ description: 'The series about an object (by object_id) or of an organisation: the quantity, measured or simulated, the step and the source. Next: read_series with its id.',
57
+ input: z.object({ object_id: uuid.optional(), quantity_code: z.string().optional(), organisation_id: uuid.optional(), limit }),
58
+ writes: false,
59
+ run: ({ db }, a) => core.listObjects(db, 'series', { object_id: a.object_id, quantity_code: a.quantity_code, organisation_id: a.organisation_id }, a.limit),
60
+ }),
61
+ ];
62
+ export const READ_TOOLS = [
63
+ tool({
64
+ name: 'status',
65
+ title: 'Status',
66
+ description: 'The schema version, who you are acting as, the modules installed, and the organisations you can read with your role on each. Call it first when something is refused or empty.',
67
+ input: z.object({}),
68
+ writes: false,
69
+ run: ({ db }) => core.status(db),
70
+ }),
71
+ ...lists,
72
+ tool({
73
+ name: 'get_object',
74
+ title: 'One object',
75
+ description: 'One object of the core by its kind and id — organisation, project, participant, meter, device or series — with its attributes in force (attributes_of()).',
76
+ input: z.object({ kind: z.enum(core.OBJECT_KINDS), id: uuid }),
77
+ writes: false,
78
+ run: ({ db }, a) => core.getObject(db, a.kind, a.id),
79
+ }),
80
+ tool({
81
+ name: 'read_series',
82
+ title: 'Read a series',
83
+ description: 'The values of a series per bucket of a regular step (resample()), in the unit of its quantity, with how many samples each bucket had and expected. A cumulative register gives its consumption per bucket. Dates are the start of each interval.',
84
+ input: z.object({ series_id: uuid, from: instant, to: instant, step: z.string().describe('A Postgres interval: 15 minutes, 1 hour, 1 day') }),
85
+ writes: false,
86
+ run: ({ db }, a) => core.readSeries(db, a.series_id, a.from, a.to, a.step),
87
+ }),
88
+ tool({
89
+ name: 'parameter_of',
90
+ title: 'A parameter of an object',
91
+ description: 'The value of a parameter (an attribute type) for an object, through the cascade of defaults: the object, then its parents, then the pack of its country and region. Null when nothing decides it — never guess one.',
92
+ input: z.object({ kind: z.string(), id: uuid, attribute_type: z.string(), at: instant.optional() }),
93
+ writes: false,
94
+ run: ({ db }, a) => core.parameterOf(db, a.kind, a.id, a.attribute_type, a.at),
95
+ }),
96
+ tool({
97
+ name: 'list_api_keys',
98
+ title: 'Keys of an organisation',
99
+ description: 'The keys of an organisation you manage (members.manage): their name, prefix, capabilities, expiry, last use and withdrawal. Never a secret.',
100
+ input: z.object({ organisation_id: uuid }),
101
+ writes: false,
102
+ run: ({ db }, a) => core.listApiKeys(db, a.organisation_id),
103
+ }),
104
+ ];
@@ -0,0 +1,30 @@
1
+ /**
2
+ * What a tool is here: a name, words for a model, an input schema, and a
3
+ * gesture of `@nexgen-os/core` run in one transaction acting as the person.
4
+ *
5
+ * Tools never see a connection. They are handed a `Db` that row level
6
+ * security binds as the person (`personSession()`), and the options the
7
+ * person configured: their geocoder, the computations of the modules.
8
+ */
9
+ import type { Computations, Db, Geocoder } from '@nexgen-os/core';
10
+ import type { z } from 'zod';
11
+ export interface ToolContext {
12
+ db: Db;
13
+ computations: Computations;
14
+ geocoder?: Geocoder | undefined;
15
+ }
16
+ export interface Tool<S extends z.ZodObject = z.ZodObject> {
17
+ name: string;
18
+ title: string;
19
+ description: string;
20
+ input: S;
21
+ /** Writes: refused by the database on a connection that reads. */
22
+ writes: boolean;
23
+ /** Changes what was there rather than adding: a client may ask before calling it. */
24
+ destructive?: boolean;
25
+ /** The module whose installation the tool needs; the core's otherwise. */
26
+ module?: string;
27
+ run(context: ToolContext, args: z.infer<S>): Promise<unknown>;
28
+ }
29
+ /** Declares a tool with its arguments typed from its schema. */
30
+ export declare function tool<S extends z.ZodObject>(definition: Tool<S>): Tool;
@@ -0,0 +1,4 @@
1
+ /** Declares a tool with its arguments typed from its schema. */
2
+ export function tool(definition) {
3
+ return definition;
4
+ }
@@ -0,0 +1,2 @@
1
+ import { type Tool } from './tool.js';
2
+ export declare const WRITE_TOOLS: Tool[];
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Describing and equipping: a project, a participant with its place, a
3
+ * meter, a device, the values of a series. Each goes through the schema's
4
+ * function for its gesture, as the person; none writes SQL of its own.
5
+ */
6
+ import * as core from '@nexgen-os/core';
7
+ import { z } from 'zod';
8
+ import { tool } from './tool.js';
9
+ const uuid = z.string().uuid();
10
+ const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe('An ISO date, 2026-06-15');
11
+ const target = {
12
+ object_kind: z.enum(['organisation', 'project', 'participant', 'meter', 'device']).describe('What the series is about'),
13
+ object_id: uuid,
14
+ organisation_id: uuid,
15
+ quantity_code: z.string().describe('A code of quantities: offtake_energy, injection_energy, production_energy…'),
16
+ kind: z.enum(['measured', 'simulated', 'forecast', 'setpoint']).default('measured'),
17
+ source_code: z.string().describe('A code of sources: where the values come from. Required: a value says where it comes from'),
18
+ name: z.string().optional().describe('Tells apart two series of the same object, quantity, kind and source'),
19
+ };
20
+ const targetOf = (a) => ({
21
+ organisationId: a.organisation_id, objectKind: a.object_kind, objectId: a.object_id, sourceCode: a.source_code, kind: a.kind, name: a.name ?? null,
22
+ });
23
+ export const WRITE_TOOLS = [
24
+ tool({
25
+ name: 'create_project',
26
+ title: 'Create a project',
27
+ description: 'Opens a project in an organisation (create_project()): its name, the ISO country whose rules apply — the person says it, never assume one — and the frame it is carried out in when it has one (kind, a code of project_kinds: a rooftop PV project, a self-consumption operation, an energy community or a legal frame of the country; none otherwise). Next: add_participant.',
28
+ input: z.object({ organisation_id: uuid, name: z.string().min(1), country: z.string().length(2), kind: z.string().optional(), start_date: date.optional() }),
29
+ writes: true,
30
+ run: ({ db }, a) => core.createProject(db, a),
31
+ }),
32
+ tool({
33
+ name: 'add_participant',
34
+ title: 'Add a participant',
35
+ description: 'A participant joins a project with its place (join_project()). Give the place in the standard shape when you have it (country, address_line1, postal_code, city, municipality, geometry as a GeoJSON Point, location_precision, location_source_code — a code of sources), or an address the geocoder chain the person configured finds — the national register of the country first, then the open fallback. Give the time zone when the person knows it; without it, no daily readings.',
36
+ input: z.object({
37
+ project_id: uuid,
38
+ name: z.string().min(1),
39
+ category: z.string().optional().describe('What it does with energy: consumer by default, producer or prosumer'),
40
+ time_zone: z.string().optional().describe('An IANA time zone, Europe/Brussels'),
41
+ place: z.record(z.string(), z.unknown()).optional(),
42
+ address: z.string().optional(),
43
+ country: z.string().length(2).optional().describe('Narrows the geocoder to one country'),
44
+ }),
45
+ writes: true,
46
+ run: ({ db, geocoder }, a) => core.addParticipant(db, a, geocoder),
47
+ }),
48
+ tool({
49
+ name: 'declare_meter',
50
+ title: 'Declare a meter',
51
+ description: 'A meter of a participant (declare_meter()), by its identifier in a scheme of identifier_schemes, which checks it. A meter measures offtake and injection; production is a device\'s.',
52
+ input: z.object({
53
+ participant_id: uuid, identifier: z.string().min(1), scheme: z.string().min(1),
54
+ resource: z.string().optional(), direction: z.enum(['offtake', 'injection', 'both']).optional(),
55
+ valid_from: date.optional(), name: z.string().optional(),
56
+ }),
57
+ writes: true,
58
+ run: ({ db }, a) => core.declareMeter(db, a),
59
+ }),
60
+ tool({
61
+ name: 'install_device',
62
+ title: 'Install a device',
63
+ description: 'A device of a participant (install_device()): its type (device_types), a name, and the product of the catalogue it is, whose power and capacity it takes, or a rated power the person states.',
64
+ input: z.object({
65
+ participant_id: uuid, device_type: z.string(), name: z.string().min(1), product_id: uuid.optional(),
66
+ rated_power_kw: z.number().positive().optional(), installed_on: date.optional(), source_code: z.string().optional(),
67
+ unit_count: z.number().int().positive().optional(),
68
+ }),
69
+ writes: true,
70
+ run: ({ db }, a) => core.installDevice(db, a),
71
+ }),
72
+ tool({
73
+ name: 'store_series',
74
+ title: 'Store series values',
75
+ description: 'Values of a series through store(), the one write path: the series of the object, quantity, kind and source, found or created once; each value dated at the START of its interval, in `unit` (converted to the unit of the quantity). A value already there is replaced. Never a value you computed yourself.',
76
+ input: z.object({
77
+ ...target,
78
+ value_kind: z.enum(['interval', 'instant', 'cumulative']).default('interval'),
79
+ step: z.string().nullable().default(null).describe('A Postgres interval, 15 minutes; null when irregular'),
80
+ unit: z.string().optional(),
81
+ values: z.array(z.object({ at: z.string(), value: z.number() })).min(1).max(100_000),
82
+ }),
83
+ writes: true,
84
+ run: ({ db }, a) => core.storeSeries(db, targetOf(a), {
85
+ quantity_code: a.quantity_code, value_kind: a.value_kind, step: a.step, values: a.values, ...(a.unit === undefined ? {} : { unit: a.unit }),
86
+ }),
87
+ }),
88
+ tool({
89
+ name: 'import_series',
90
+ title: 'Import series from a file',
91
+ description: 'The readings of a file, read by its format library and written through store(). Formats: homeassistant — a Home Assistant export (registries and recorder states, as JSON text) and the entity whose readings to keep. The file travels as text.',
92
+ input: z.object({
93
+ ...target,
94
+ format: z.enum(['homeassistant']),
95
+ file: z.string().max(10_000_000).describe('The content of the file'),
96
+ entity_id: z.string().describe('The entity of the export: sensor.grid_import'),
97
+ }),
98
+ writes: true,
99
+ run: ({ db }, a) => core.importHomeAssistantSeries(db, targetOf(a), JSON.parse(a.file), a.entity_id, a.quantity_code),
100
+ }),
101
+ tool({
102
+ name: 'create_api_key',
103
+ title: 'Issue a key',
104
+ description: 'A key for a machine or another agent, issued on an organisation by a person who holds members.manage on it, signed in: it acts as them within that organisation and the capabilities on its list (data.read, data.write…, see my_capabilities), read only unless it carries one that writes. The secret is in this answer once; give it to the person, never store it. A key does not issue keys.',
105
+ input: z.object({ organisation_id: uuid, name: z.string().min(1), capabilities: z.array(z.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/)).min(1).default(['data.read']), expires_at: z.string().optional() }),
106
+ writes: true,
107
+ run: ({ db }, a) => core.createApiKey(db, a),
108
+ }),
109
+ tool({
110
+ name: 'revoke_api_key',
111
+ title: 'Withdraw a key',
112
+ description: 'Withdraws a key of an organisation you own, at once and for good. Only on the person\'s word.',
113
+ input: z.object({ api_key_id: uuid }),
114
+ writes: true,
115
+ destructive: true,
116
+ run: ({ db }, a) => core.revokeApiKey(db, a.api_key_id),
117
+ }),
118
+ ];
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The server before anybody has told it where the database is.
3
+ *
4
+ * A client lists a server's tools the moment it is added, and so do the
5
+ * directories that index servers. So when the connection is simply absent
6
+ * the server starts anyway, and every call answers with what to set.
7
+ * Nothing is connected and nothing is guessed.
8
+ */
9
+ import { type Session } from '@nexgen-os/core';
10
+ /** Whether a configuration error only says that something is missing. */
11
+ export declare function isMissingConfiguration(error: unknown): boolean;
12
+ export declare function unconfiguredSession(reason: Error): Session;