@ansvar/ch-environmental-compliance-mcp 0.1.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/.github/workflows/check-freshness.yml +49 -0
- package/.github/workflows/ci.yml +21 -0
- package/.github/workflows/codeql.yml +25 -0
- package/.github/workflows/ghcr-build.yml +45 -0
- package/.github/workflows/gitleaks.yml +18 -0
- package/.github/workflows/ingest.yml +59 -0
- package/.github/workflows/publish.yml +24 -0
- package/CHANGELOG.md +15 -0
- package/CODEOWNERS +1 -0
- package/COVERAGE.md +50 -0
- package/DISCLAIMER.md +48 -0
- package/Dockerfile +26 -0
- package/LICENSE +17 -0
- package/PRIVACY.md +23 -0
- package/README.md +116 -0
- package/SECURITY.md +25 -0
- package/TOOLS.md +142 -0
- package/data/coverage.json +24 -0
- package/data/database.db +0 -0
- package/data/sources.yml +36 -0
- package/dist/db.d.ts +25 -0
- package/dist/db.d.ts.map +1 -0
- package/dist/db.js +197 -0
- package/dist/db.js.map +1 -0
- package/dist/http-server.d.ts +2 -0
- package/dist/http-server.d.ts.map +1 -0
- package/dist/http-server.js +274 -0
- package/dist/http-server.js.map +1 -0
- package/dist/jurisdiction.d.ts +18 -0
- package/dist/jurisdiction.d.ts.map +1 -0
- package/dist/jurisdiction.js +16 -0
- package/dist/jurisdiction.js.map +1 -0
- package/dist/metadata.d.ts +10 -0
- package/dist/metadata.d.ts.map +1 -0
- package/dist/metadata.js +22 -0
- package/dist/metadata.js.map +1 -0
- package/dist/server.d.ts +3 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +220 -0
- package/dist/server.js.map +1 -0
- package/dist/tools/about.d.ts +15 -0
- package/dist/tools/about.d.ts.map +1 -0
- package/dist/tools/about.js +27 -0
- package/dist/tools/about.js.map +1 -0
- package/dist/tools/check-environmental-compliance.d.ts +30 -0
- package/dist/tools/check-environmental-compliance.d.ts.map +1 -0
- package/dist/tools/check-environmental-compliance.js +103 -0
- package/dist/tools/check-environmental-compliance.js.map +1 -0
- package/dist/tools/check-freshness.d.ts +15 -0
- package/dist/tools/check-freshness.d.ts.map +1 -0
- package/dist/tools/check-freshness.js +26 -0
- package/dist/tools/check-freshness.js.map +1 -0
- package/dist/tools/get-ammonia-rules.d.ts +24 -0
- package/dist/tools/get-ammonia-rules.d.ts.map +1 -0
- package/dist/tools/get-ammonia-rules.js +31 -0
- package/dist/tools/get-ammonia-rules.js.map +1 -0
- package/dist/tools/get-bff-requirements.d.ts +26 -0
- package/dist/tools/get-bff-requirements.d.ts.map +1 -0
- package/dist/tools/get-bff-requirements.js +36 -0
- package/dist/tools/get-bff-requirements.js.map +1 -0
- package/dist/tools/get-buffer-zone-rules.d.ts +23 -0
- package/dist/tools/get-buffer-zone-rules.d.ts.map +1 -0
- package/dist/tools/get-buffer-zone-rules.js +30 -0
- package/dist/tools/get-buffer-zone-rules.js.map +1 -0
- package/dist/tools/get-eip-requirements.d.ts +31 -0
- package/dist/tools/get-eip-requirements.d.ts.map +1 -0
- package/dist/tools/get-eip-requirements.js +40 -0
- package/dist/tools/get-eip-requirements.js.map +1 -0
- package/dist/tools/get-nutrient-loss-limits.d.ts +24 -0
- package/dist/tools/get-nutrient-loss-limits.d.ts.map +1 -0
- package/dist/tools/get-nutrient-loss-limits.js +31 -0
- package/dist/tools/get-nutrient-loss-limits.js.map +1 -0
- package/dist/tools/get-water-protection-zones.d.ts +32 -0
- package/dist/tools/get-water-protection-zones.d.ts.map +1 -0
- package/dist/tools/get-water-protection-zones.js +36 -0
- package/dist/tools/get-water-protection-zones.js.map +1 -0
- package/dist/tools/list-sources.d.ts +18 -0
- package/dist/tools/list-sources.d.ts.map +1 -0
- package/dist/tools/list-sources.js +61 -0
- package/dist/tools/list-sources.js.map +1 -0
- package/dist/tools/search-environmental-rules.d.ts +25 -0
- package/dist/tools/search-environmental-rules.d.ts.map +1 -0
- package/dist/tools/search-environmental-rules.js +26 -0
- package/dist/tools/search-environmental-rules.js.map +1 -0
- package/docker-compose.yml +12 -0
- package/eslint.config.js +26 -0
- package/package.json +54 -0
- package/scripts/ingest.ts +911 -0
- package/server.json +16 -0
- package/src/db.ts +238 -0
- package/src/http-server.ts +307 -0
- package/src/jurisdiction.ts +30 -0
- package/src/metadata.ts +32 -0
- package/src/server.ts +244 -0
- package/src/tools/about.ts +28 -0
- package/src/tools/check-environmental-compliance.ts +143 -0
- package/src/tools/check-freshness.ts +42 -0
- package/src/tools/get-ammonia-rules.ts +44 -0
- package/src/tools/get-bff-requirements.ts +52 -0
- package/src/tools/get-buffer-zone-rules.ts +43 -0
- package/src/tools/get-eip-requirements.ts +57 -0
- package/src/tools/get-nutrient-loss-limits.ts +44 -0
- package/src/tools/get-water-protection-zones.ts +50 -0
- package/src/tools/list-sources.ts +75 -0
- package/src/tools/search-environmental-rules.ts +35 -0
- package/tests/db.test.ts +80 -0
- package/tests/helpers/seed-db.ts +173 -0
- package/tests/jurisdiction.test.ts +35 -0
- package/tests/tools/about.test.ts +26 -0
- package/tests/tools/check-freshness.test.ts +50 -0
- package/tests/tools/list-sources.test.ts +61 -0
- package/tests/tools/search-environmental-rules.test.ts +47 -0
- package/tsconfig.json +19 -0
package/server.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
|
+
"name": "io.github.Ansvar-Systems/ch-environmental-compliance",
|
|
4
|
+
"description": "Swiss environmental compliance -- GSchG, LRV, BFF, ammonia rules, Pa.Iv. 19.475, UVP, VBBo",
|
|
5
|
+
"repository": {
|
|
6
|
+
"url": "https://github.com/Ansvar-Systems/ch-environmental-compliance-mcp",
|
|
7
|
+
"source": "github"
|
|
8
|
+
},
|
|
9
|
+
"version": "0.1.0",
|
|
10
|
+
"remotes": [
|
|
11
|
+
{
|
|
12
|
+
"type": "streamable-http",
|
|
13
|
+
"url": "https://mcp.ansvar.eu/ch-environmental-compliance/mcp"
|
|
14
|
+
}
|
|
15
|
+
]
|
|
16
|
+
}
|
package/src/db.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import BetterSqlite3 from 'better-sqlite3';
|
|
2
|
+
import { join, dirname } from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
|
|
5
|
+
export interface Database {
|
|
6
|
+
get<T>(sql: string, params?: unknown[]): T | undefined;
|
|
7
|
+
all<T>(sql: string, params?: unknown[]): T[];
|
|
8
|
+
run(sql: string, params?: unknown[]): void;
|
|
9
|
+
close(): void;
|
|
10
|
+
readonly instance: BetterSqlite3.Database;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function createDatabase(dbPath?: string): Database {
|
|
14
|
+
const resolvedPath =
|
|
15
|
+
dbPath ??
|
|
16
|
+
join(dirname(fileURLToPath(import.meta.url)), '..', 'data', 'database.db');
|
|
17
|
+
const db = new BetterSqlite3(resolvedPath);
|
|
18
|
+
|
|
19
|
+
db.pragma('journal_mode = DELETE');
|
|
20
|
+
db.pragma('foreign_keys = ON');
|
|
21
|
+
|
|
22
|
+
initSchema(db);
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
get<T>(sql: string, params: unknown[] = []): T | undefined {
|
|
26
|
+
return db.prepare(sql).get(...params) as T | undefined;
|
|
27
|
+
},
|
|
28
|
+
all<T>(sql: string, params: unknown[] = []): T[] {
|
|
29
|
+
return db.prepare(sql).all(...params) as T[];
|
|
30
|
+
},
|
|
31
|
+
run(sql: string, params: unknown[] = []): void {
|
|
32
|
+
db.prepare(sql).run(...params);
|
|
33
|
+
},
|
|
34
|
+
close(): void {
|
|
35
|
+
db.close();
|
|
36
|
+
},
|
|
37
|
+
get instance() {
|
|
38
|
+
return db;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function initSchema(db: BetterSqlite3.Database): void {
|
|
44
|
+
db.exec(`
|
|
45
|
+
CREATE TABLE IF NOT EXISTS water_protection_zones (
|
|
46
|
+
id INTEGER PRIMARY KEY,
|
|
47
|
+
zone_type TEXT NOT NULL,
|
|
48
|
+
name TEXT NOT NULL,
|
|
49
|
+
restrictions TEXT NOT NULL,
|
|
50
|
+
description TEXT NOT NULL,
|
|
51
|
+
legal_basis TEXT,
|
|
52
|
+
jurisdiction TEXT NOT NULL DEFAULT 'CH',
|
|
53
|
+
language TEXT NOT NULL DEFAULT 'DE'
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
CREATE TABLE IF NOT EXISTS buffer_zones (
|
|
57
|
+
id INTEGER PRIMARY KEY,
|
|
58
|
+
type TEXT NOT NULL,
|
|
59
|
+
distance_m REAL NOT NULL,
|
|
60
|
+
requirement TEXT NOT NULL,
|
|
61
|
+
source_law TEXT NOT NULL,
|
|
62
|
+
notes TEXT,
|
|
63
|
+
jurisdiction TEXT NOT NULL DEFAULT 'CH',
|
|
64
|
+
language TEXT NOT NULL DEFAULT 'DE'
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
CREATE TABLE IF NOT EXISTS ammonia_rules (
|
|
68
|
+
id INTEGER PRIMARY KEY,
|
|
69
|
+
technique TEXT NOT NULL,
|
|
70
|
+
emission_factor REAL,
|
|
71
|
+
requirement TEXT NOT NULL,
|
|
72
|
+
legal_basis TEXT,
|
|
73
|
+
effective_date TEXT,
|
|
74
|
+
notes TEXT,
|
|
75
|
+
jurisdiction TEXT NOT NULL DEFAULT 'CH',
|
|
76
|
+
language TEXT NOT NULL DEFAULT 'DE'
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
CREATE TABLE IF NOT EXISTS bff_types (
|
|
80
|
+
id TEXT PRIMARY KEY,
|
|
81
|
+
name TEXT NOT NULL,
|
|
82
|
+
quality_level TEXT NOT NULL,
|
|
83
|
+
payment_chf_ha REAL,
|
|
84
|
+
min_area_pct REAL,
|
|
85
|
+
botanical_criteria TEXT,
|
|
86
|
+
notes TEXT,
|
|
87
|
+
jurisdiction TEXT NOT NULL DEFAULT 'CH',
|
|
88
|
+
language TEXT NOT NULL DEFAULT 'DE'
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
CREATE TABLE IF NOT EXISTS nutrient_loss_limits (
|
|
92
|
+
id INTEGER PRIMARY KEY,
|
|
93
|
+
nutrient TEXT NOT NULL,
|
|
94
|
+
year INTEGER NOT NULL,
|
|
95
|
+
limit_pct REAL NOT NULL,
|
|
96
|
+
target TEXT NOT NULL,
|
|
97
|
+
legal_basis TEXT,
|
|
98
|
+
notes TEXT,
|
|
99
|
+
jurisdiction TEXT NOT NULL DEFAULT 'CH',
|
|
100
|
+
language TEXT NOT NULL DEFAULT 'DE'
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
CREATE TABLE IF NOT EXISTS environmental_rules (
|
|
104
|
+
id INTEGER PRIMARY KEY,
|
|
105
|
+
topic TEXT NOT NULL,
|
|
106
|
+
rule TEXT NOT NULL,
|
|
107
|
+
authority TEXT NOT NULL,
|
|
108
|
+
legal_basis TEXT NOT NULL,
|
|
109
|
+
threshold TEXT,
|
|
110
|
+
notes TEXT,
|
|
111
|
+
jurisdiction TEXT NOT NULL DEFAULT 'CH',
|
|
112
|
+
language TEXT NOT NULL DEFAULT 'DE'
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS search_index USING fts5(
|
|
116
|
+
title, body, topic, jurisdiction
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
CREATE TABLE IF NOT EXISTS db_metadata (
|
|
120
|
+
key TEXT PRIMARY KEY,
|
|
121
|
+
value TEXT
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
INSERT OR IGNORE INTO db_metadata (key, value) VALUES ('schema_version', '1.0');
|
|
125
|
+
INSERT OR IGNORE INTO db_metadata (key, value) VALUES ('mcp_name', 'Switzerland Environmental Compliance MCP');
|
|
126
|
+
INSERT OR IGNORE INTO db_metadata (key, value) VALUES ('jurisdiction', 'CH');
|
|
127
|
+
`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const FTS_COLUMNS = ['title', 'body', 'topic', 'jurisdiction'];
|
|
131
|
+
|
|
132
|
+
export function ftsSearch(
|
|
133
|
+
db: Database,
|
|
134
|
+
query: string,
|
|
135
|
+
limit: number = 20
|
|
136
|
+
): { title: string; body: string; topic: string; jurisdiction: string; rank: number }[] {
|
|
137
|
+
const { results } = tieredFtsSearch(db, 'search_index', FTS_COLUMNS, query, limit);
|
|
138
|
+
return results as { title: string; body: string; topic: string; jurisdiction: string; rank: number }[];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Tiered FTS5 search with automatic fallback.
|
|
143
|
+
* Tiers: exact phrase -> AND -> prefix -> stemmed prefix -> OR -> LIKE
|
|
144
|
+
*/
|
|
145
|
+
export function tieredFtsSearch(
|
|
146
|
+
db: Database,
|
|
147
|
+
table: string,
|
|
148
|
+
columns: string[],
|
|
149
|
+
query: string,
|
|
150
|
+
limit: number = 20
|
|
151
|
+
): { tier: string; results: Record<string, unknown>[] } {
|
|
152
|
+
const sanitized = sanitizeFtsInput(query);
|
|
153
|
+
if (!sanitized.trim()) return { tier: 'empty', results: [] };
|
|
154
|
+
|
|
155
|
+
const columnList = columns.join(', ');
|
|
156
|
+
const select = `SELECT ${columnList}, rank FROM ${table}`;
|
|
157
|
+
const order = `ORDER BY rank LIMIT ?`;
|
|
158
|
+
|
|
159
|
+
// Tier 1: Exact phrase
|
|
160
|
+
const phrase = `"${sanitized}"`;
|
|
161
|
+
let results = tryFts(db, select, table, order, phrase, limit);
|
|
162
|
+
if (results.length > 0) return { tier: 'phrase', results };
|
|
163
|
+
|
|
164
|
+
// Tier 2: AND
|
|
165
|
+
const words = sanitized.split(/\s+/).filter(w => w.length > 1);
|
|
166
|
+
if (words.length > 1) {
|
|
167
|
+
const andQuery = words.join(' AND ');
|
|
168
|
+
results = tryFts(db, select, table, order, andQuery, limit);
|
|
169
|
+
if (results.length > 0) return { tier: 'and', results };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Tier 3: Prefix
|
|
173
|
+
const prefixQuery = words.map(w => `${w}*`).join(' AND ');
|
|
174
|
+
results = tryFts(db, select, table, order, prefixQuery, limit);
|
|
175
|
+
if (results.length > 0) return { tier: 'prefix', results };
|
|
176
|
+
|
|
177
|
+
// Tier 4: Stemmed prefix
|
|
178
|
+
const stemmed = words.map(w => stemWord(w) + '*');
|
|
179
|
+
const stemmedQuery = stemmed.join(' AND ');
|
|
180
|
+
if (stemmedQuery !== prefixQuery) {
|
|
181
|
+
results = tryFts(db, select, table, order, stemmedQuery, limit);
|
|
182
|
+
if (results.length > 0) return { tier: 'stemmed', results };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Tier 5: OR
|
|
186
|
+
if (words.length > 1) {
|
|
187
|
+
const orQuery = words.join(' OR ');
|
|
188
|
+
results = tryFts(db, select, table, order, orQuery, limit);
|
|
189
|
+
if (results.length > 0) return { tier: 'or', results };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Tier 6: LIKE fallback
|
|
193
|
+
const baseCols = ['topic', 'rule'];
|
|
194
|
+
const likeConditions = words.map(() =>
|
|
195
|
+
`(${baseCols.map(c => `${c} LIKE ?`).join(' OR ')})`
|
|
196
|
+
).join(' AND ');
|
|
197
|
+
const likeParams = words.flatMap(w =>
|
|
198
|
+
baseCols.map(() => `%${w}%`)
|
|
199
|
+
);
|
|
200
|
+
try {
|
|
201
|
+
const likeResults = db.all<Record<string, unknown>>(
|
|
202
|
+
`SELECT topic as title, rule as body, topic, jurisdiction FROM environmental_rules WHERE ${likeConditions} LIMIT ?`,
|
|
203
|
+
[...likeParams, limit]
|
|
204
|
+
);
|
|
205
|
+
if (likeResults.length > 0) return { tier: 'like', results: likeResults };
|
|
206
|
+
} catch {
|
|
207
|
+
// LIKE fallback failed
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return { tier: 'none', results: [] };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function tryFts(
|
|
214
|
+
db: Database, select: string, table: string,
|
|
215
|
+
order: string, matchExpr: string, limit: number
|
|
216
|
+
): Record<string, unknown>[] {
|
|
217
|
+
try {
|
|
218
|
+
return db.all(
|
|
219
|
+
`${select} WHERE ${table} MATCH ? ${order}`,
|
|
220
|
+
[matchExpr, limit]
|
|
221
|
+
);
|
|
222
|
+
} catch {
|
|
223
|
+
return [];
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function sanitizeFtsInput(query: string): string {
|
|
228
|
+
return query
|
|
229
|
+
.replace(/["""'',,,,]/g, '"')
|
|
230
|
+
.replace(/[^a-zA-Z0-9\s*"_\u00C0-\u024F-]/g, ' ')
|
|
231
|
+
.replace(/\s+/g, ' ')
|
|
232
|
+
.trim();
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function stemWord(word: string): string {
|
|
236
|
+
return word
|
|
237
|
+
.replace(/(ung|heit|keit|lich|isch|ieren|tion|ment|ness|able|ible|ous|ive|ing|ers|ed|es|er|en|ly|s)$/i, '');
|
|
238
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { createServer, type IncomingMessage, type ServerResponse } from 'http';
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
4
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
5
|
+
import {
|
|
6
|
+
ListToolsRequestSchema,
|
|
7
|
+
CallToolRequestSchema,
|
|
8
|
+
} from '@modelcontextprotocol/sdk/types.js';
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
import { createDatabase, type Database } from './db.js';
|
|
11
|
+
import { handleAbout } from './tools/about.js';
|
|
12
|
+
import { handleListSources } from './tools/list-sources.js';
|
|
13
|
+
import { handleCheckFreshness } from './tools/check-freshness.js';
|
|
14
|
+
import { handleSearchEnvironmentalRules } from './tools/search-environmental-rules.js';
|
|
15
|
+
import { handleGetWaterProtectionZones } from './tools/get-water-protection-zones.js';
|
|
16
|
+
import { handleGetBufferZoneRules } from './tools/get-buffer-zone-rules.js';
|
|
17
|
+
import { handleGetAmmoniaRules } from './tools/get-ammonia-rules.js';
|
|
18
|
+
import { handleGetBffRequirements } from './tools/get-bff-requirements.js';
|
|
19
|
+
import { handleGetNutrientLossLimits } from './tools/get-nutrient-loss-limits.js';
|
|
20
|
+
import { handleGetEipRequirements } from './tools/get-eip-requirements.js';
|
|
21
|
+
import { handleCheckEnvironmentalCompliance } from './tools/check-environmental-compliance.js';
|
|
22
|
+
|
|
23
|
+
const SERVER_NAME = 'ch-environmental-compliance-mcp';
|
|
24
|
+
const SERVER_VERSION = '0.1.0';
|
|
25
|
+
const PORT = parseInt(process.env.PORT ?? '3000', 10);
|
|
26
|
+
|
|
27
|
+
const SearchArgsSchema = z.object({
|
|
28
|
+
query: z.string(),
|
|
29
|
+
topic: z.string().optional(),
|
|
30
|
+
jurisdiction: z.string().optional(),
|
|
31
|
+
limit: z.number().optional(),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const WaterProtectionArgsSchema = z.object({
|
|
35
|
+
zone_type: z.string().optional(),
|
|
36
|
+
jurisdiction: z.string().optional(),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const BufferZoneArgsSchema = z.object({
|
|
40
|
+
zone_type: z.string().optional(),
|
|
41
|
+
jurisdiction: z.string().optional(),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const AmmoniaArgsSchema = z.object({
|
|
45
|
+
technique: z.string().optional(),
|
|
46
|
+
jurisdiction: z.string().optional(),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const BffArgsSchema = z.object({
|
|
50
|
+
bff_type: z.string().optional(),
|
|
51
|
+
quality_level: z.string().optional(),
|
|
52
|
+
jurisdiction: z.string().optional(),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const NutrientLossArgsSchema = z.object({
|
|
56
|
+
nutrient: z.string().optional(),
|
|
57
|
+
jurisdiction: z.string().optional(),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const EipArgsSchema = z.object({
|
|
61
|
+
project_type: z.string().optional(),
|
|
62
|
+
jurisdiction: z.string().optional(),
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const ComplianceArgsSchema = z.object({
|
|
66
|
+
facility_type: z.string(),
|
|
67
|
+
animal_count: z.number().optional(),
|
|
68
|
+
area_ha: z.number().optional(),
|
|
69
|
+
jurisdiction: z.string().optional(),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const TOOLS = [
|
|
73
|
+
{
|
|
74
|
+
name: 'about',
|
|
75
|
+
description: 'Get server metadata: name, version, coverage, data sources, and links.',
|
|
76
|
+
inputSchema: { type: 'object' as const, properties: {} },
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
name: 'list_sources',
|
|
80
|
+
description: 'List all data sources with authority, URL, license, and freshness info.',
|
|
81
|
+
inputSchema: { type: 'object' as const, properties: {} },
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: 'check_data_freshness',
|
|
85
|
+
description: 'Check when data was last ingested, staleness status, and how to trigger a refresh.',
|
|
86
|
+
inputSchema: { type: 'object' as const, properties: {} },
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: 'search_environmental_rules',
|
|
90
|
+
description: 'Search Swiss environmental compliance rules across all topics: Gewaesserschutz, Ammoniak, BFF, Pufferstreifen, VBBo, UVP.',
|
|
91
|
+
inputSchema: {
|
|
92
|
+
type: 'object' as const,
|
|
93
|
+
properties: {
|
|
94
|
+
query: { type: 'string', description: 'Free-text search query (German or English)' },
|
|
95
|
+
topic: { type: 'string', description: 'Filter by topic (e.g. Gewaesserschutz, Ammoniak, BFF, UVP, VBBo)' },
|
|
96
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
97
|
+
limit: { type: 'number', description: 'Max results (default: 20, max: 50)' },
|
|
98
|
+
},
|
|
99
|
+
required: ['query'],
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
name: 'get_water_protection_zones',
|
|
104
|
+
description: 'Get Grundwasserschutzzonen (S1, S2, S3, Sm, Zu) with restrictions and legal basis. Based on GSchG/GSchV.',
|
|
105
|
+
inputSchema: {
|
|
106
|
+
type: 'object' as const,
|
|
107
|
+
properties: {
|
|
108
|
+
zone_type: { type: 'string', description: 'Zone type: S1, S2, S3, Sm, Zu (omit for all zones)' },
|
|
109
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
name: 'get_buffer_zone_rules',
|
|
115
|
+
description: 'Get Pufferstreifen distances and requirements along water bodies, hedges, and boundaries. Based on OELN/ChemRRV.',
|
|
116
|
+
inputSchema: {
|
|
117
|
+
type: 'object' as const,
|
|
118
|
+
properties: {
|
|
119
|
+
zone_type: { type: 'string', description: 'Buffer type filter (e.g. Gewaesser, Hecke, Nachbar, SPe)' },
|
|
120
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
name: 'get_ammonia_rules',
|
|
126
|
+
description: 'Get Ammoniakemissionen rules: emission factors by technique, Schleppschlauch-Pflicht, Agrammon parameters. Based on LRV.',
|
|
127
|
+
inputSchema: {
|
|
128
|
+
type: 'object' as const,
|
|
129
|
+
properties: {
|
|
130
|
+
technique: { type: 'string', description: 'Application technique filter (e.g. Schleppschlauch, Prallteller, Injektion)' },
|
|
131
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
name: 'get_bff_requirements',
|
|
137
|
+
description: 'Get BFF types, QI/QII payment rates, minimum area requirements, and botanical criteria. Based on DZV.',
|
|
138
|
+
inputSchema: {
|
|
139
|
+
type: 'object' as const,
|
|
140
|
+
properties: {
|
|
141
|
+
bff_type: { type: 'string', description: 'BFF type filter (e.g. extensiv-wiese, buntbrache, hecke)' },
|
|
142
|
+
quality_level: { type: 'string', description: 'Quality level: QI or QII' },
|
|
143
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
name: 'get_nutrient_loss_limits',
|
|
149
|
+
description: 'Get Pa.Iv. 19.475 nutrient loss reduction targets for N and P through 2030.',
|
|
150
|
+
inputSchema: {
|
|
151
|
+
type: 'object' as const,
|
|
152
|
+
properties: {
|
|
153
|
+
nutrient: { type: 'string', description: 'Nutrient filter: N or P' },
|
|
154
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
name: 'get_eip_requirements',
|
|
160
|
+
description: 'Get UVP thresholds for agricultural buildings and VBBo Richtwerte for soil contamination.',
|
|
161
|
+
inputSchema: {
|
|
162
|
+
type: 'object' as const,
|
|
163
|
+
properties: {
|
|
164
|
+
project_type: { type: 'string', description: 'Project type filter (e.g. Stallbau, Biogasanlage)' },
|
|
165
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
name: 'check_environmental_compliance',
|
|
171
|
+
description: 'Check which environmental rules apply to a given agricultural operation.',
|
|
172
|
+
inputSchema: {
|
|
173
|
+
type: 'object' as const,
|
|
174
|
+
properties: {
|
|
175
|
+
facility_type: { type: 'string', description: 'Type of operation (e.g. Milchwirtschaft, Schweinehaltung, Ackerbau)' },
|
|
176
|
+
animal_count: { type: 'number', description: 'Number of animals (GVE) — used for ammonia and UVP thresholds' },
|
|
177
|
+
area_ha: { type: 'number', description: 'Farm area in hectares — used for BFF minimum calculations' },
|
|
178
|
+
jurisdiction: { type: 'string', description: 'ISO 3166-1 alpha-2 code (default: CH)' },
|
|
179
|
+
},
|
|
180
|
+
required: ['facility_type'],
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
];
|
|
184
|
+
|
|
185
|
+
function textResult(data: unknown) {
|
|
186
|
+
return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function errorResult(message: string) {
|
|
190
|
+
return { content: [{ type: 'text' as const, text: JSON.stringify({ error: message }) }], isError: true };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function registerTools(server: Server, db: Database): void {
|
|
194
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
195
|
+
|
|
196
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
197
|
+
const { name, arguments: args = {} } = request.params;
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
switch (name) {
|
|
201
|
+
case 'about':
|
|
202
|
+
return textResult(handleAbout());
|
|
203
|
+
case 'list_sources':
|
|
204
|
+
return textResult(handleListSources(db));
|
|
205
|
+
case 'check_data_freshness':
|
|
206
|
+
return textResult(handleCheckFreshness(db));
|
|
207
|
+
case 'search_environmental_rules':
|
|
208
|
+
return textResult(handleSearchEnvironmentalRules(db, SearchArgsSchema.parse(args)));
|
|
209
|
+
case 'get_water_protection_zones':
|
|
210
|
+
return textResult(handleGetWaterProtectionZones(db, WaterProtectionArgsSchema.parse(args)));
|
|
211
|
+
case 'get_buffer_zone_rules':
|
|
212
|
+
return textResult(handleGetBufferZoneRules(db, BufferZoneArgsSchema.parse(args)));
|
|
213
|
+
case 'get_ammonia_rules':
|
|
214
|
+
return textResult(handleGetAmmoniaRules(db, AmmoniaArgsSchema.parse(args)));
|
|
215
|
+
case 'get_bff_requirements':
|
|
216
|
+
return textResult(handleGetBffRequirements(db, BffArgsSchema.parse(args)));
|
|
217
|
+
case 'get_nutrient_loss_limits':
|
|
218
|
+
return textResult(handleGetNutrientLossLimits(db, NutrientLossArgsSchema.parse(args)));
|
|
219
|
+
case 'get_eip_requirements':
|
|
220
|
+
return textResult(handleGetEipRequirements(db, EipArgsSchema.parse(args)));
|
|
221
|
+
case 'check_environmental_compliance':
|
|
222
|
+
return textResult(handleCheckEnvironmentalCompliance(db, ComplianceArgsSchema.parse(args)));
|
|
223
|
+
default:
|
|
224
|
+
return errorResult(`Unknown tool: ${name}`);
|
|
225
|
+
}
|
|
226
|
+
} catch (err) {
|
|
227
|
+
return errorResult(err instanceof Error ? err.message : String(err));
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const db = createDatabase();
|
|
233
|
+
const sessions = new Map<string, { transport: StreamableHTTPServerTransport; server: Server }>();
|
|
234
|
+
|
|
235
|
+
function createMcpServer(): Server {
|
|
236
|
+
const mcpServer = new Server(
|
|
237
|
+
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
238
|
+
{ capabilities: { tools: {} } }
|
|
239
|
+
);
|
|
240
|
+
registerTools(mcpServer, db);
|
|
241
|
+
return mcpServer;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function handleMCPRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
245
|
+
const sessionId = req.headers['mcp-session-id'] as string | undefined;
|
|
246
|
+
|
|
247
|
+
if (sessionId && sessions.has(sessionId)) {
|
|
248
|
+
const session = sessions.get(sessionId)!;
|
|
249
|
+
await session.transport.handleRequest(req, res);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (req.method === 'GET' || req.method === 'DELETE') {
|
|
254
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
255
|
+
res.end(JSON.stringify({ error: 'Invalid or missing session ID' }));
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const mcpServer = createMcpServer();
|
|
260
|
+
const transport = new StreamableHTTPServerTransport({
|
|
261
|
+
sessionIdGenerator: () => randomUUID(),
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
await mcpServer.connect(transport);
|
|
265
|
+
|
|
266
|
+
transport.onclose = () => {
|
|
267
|
+
if (transport.sessionId) {
|
|
268
|
+
sessions.delete(transport.sessionId);
|
|
269
|
+
}
|
|
270
|
+
mcpServer.close().catch(() => {});
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
await transport.handleRequest(req, res);
|
|
274
|
+
|
|
275
|
+
if (transport.sessionId) {
|
|
276
|
+
sessions.set(transport.sessionId, { transport, server: mcpServer });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const httpServer = createServer(async (req, res) => {
|
|
281
|
+
const url = new URL(req.url || '/', `http://localhost:${PORT}`);
|
|
282
|
+
|
|
283
|
+
if (url.pathname === '/health' && req.method === 'GET') {
|
|
284
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
285
|
+
res.end(JSON.stringify({ status: 'healthy', server: SERVER_NAME, version: SERVER_VERSION }));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (url.pathname === '/mcp' || url.pathname === '/') {
|
|
290
|
+
try {
|
|
291
|
+
await handleMCPRequest(req, res);
|
|
292
|
+
} catch (err) {
|
|
293
|
+
if (!res.headersSent) {
|
|
294
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
295
|
+
res.end(JSON.stringify({ error: err instanceof Error ? err.message : 'Internal server error' }));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
302
|
+
res.end(JSON.stringify({ error: 'Not found' }));
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
httpServer.listen(PORT, () => {
|
|
306
|
+
console.log(`${SERVER_NAME} v${SERVER_VERSION} listening on port ${PORT}`);
|
|
307
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const SUPPORTED_JURISDICTIONS = ['CH'] as const;
|
|
2
|
+
export type Jurisdiction = (typeof SUPPORTED_JURISDICTIONS)[number];
|
|
3
|
+
|
|
4
|
+
type ValidationSuccess = { valid: true; jurisdiction: Jurisdiction };
|
|
5
|
+
type ValidationFailure = {
|
|
6
|
+
valid: false;
|
|
7
|
+
error: {
|
|
8
|
+
error: string;
|
|
9
|
+
supported: readonly string[];
|
|
10
|
+
message: string;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
type ValidationResult = ValidationSuccess | ValidationFailure;
|
|
14
|
+
|
|
15
|
+
export function validateJurisdiction(input: string | undefined): ValidationResult {
|
|
16
|
+
const normalised = (input ?? 'CH').toUpperCase();
|
|
17
|
+
|
|
18
|
+
if (SUPPORTED_JURISDICTIONS.includes(normalised as Jurisdiction)) {
|
|
19
|
+
return { valid: true, jurisdiction: normalised as Jurisdiction };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
valid: false,
|
|
24
|
+
error: {
|
|
25
|
+
error: 'jurisdiction_not_supported',
|
|
26
|
+
supported: SUPPORTED_JURISDICTIONS,
|
|
27
|
+
message: 'This server currently covers Switzerland. More jurisdictions are planned.',
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
package/src/metadata.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface Meta {
|
|
2
|
+
disclaimer: string;
|
|
3
|
+
data_age: string;
|
|
4
|
+
source_url: string;
|
|
5
|
+
copyright: string;
|
|
6
|
+
server: string;
|
|
7
|
+
version: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const DISCLAIMER =
|
|
11
|
+
'Diese Daten dienen ausschliesslich der Information und stellen keine rechtliche oder umweltfachliche ' +
|
|
12
|
+
'Beratung dar. Vor Massnahmen im Gewaesserschutz, bei Ammoniakemissionen oder Biodiversitaetsfoerderflaechen ' +
|
|
13
|
+
'ist stets die zustaendige kantonale Fachstelle oder das BAFU zu konsultieren. Die Daten basieren auf dem ' +
|
|
14
|
+
'Gewaesserschutzgesetz (GSchG, SR 814.20), der Gewaesserschutzverordnung (GSchV, SR 814.201), der ' +
|
|
15
|
+
'Luftreinhalte-Verordnung (LRV, SR 814.318.142.1), der Direktzahlungsverordnung (DZV, SR 910.13) sowie ' +
|
|
16
|
+
'Publikationen von BAFU, BLW und Agroscope. Kantonale Abweichungen und betriebsspezifische Auflagen sind ' +
|
|
17
|
+
'eigenstaendig zu pruefen. / ' +
|
|
18
|
+
'This data is provided for informational purposes only and does not constitute legal or environmental ' +
|
|
19
|
+
'compliance advice. Always consult the relevant cantonal authority or BAFU before taking action. Data sourced ' +
|
|
20
|
+
'from GSchG, LRV, DZV, BAFU, BLW, and Agroscope publications.';
|
|
21
|
+
|
|
22
|
+
export function buildMeta(overrides?: Partial<Meta>): Meta {
|
|
23
|
+
return {
|
|
24
|
+
disclaimer: DISCLAIMER,
|
|
25
|
+
data_age: overrides?.data_age ?? 'unknown',
|
|
26
|
+
source_url: overrides?.source_url ?? 'https://www.bafu.admin.ch/bafu/de/home/themen/wasser/fachinformationen/gewaesserschutz.html',
|
|
27
|
+
copyright: 'Data: BAFU, BLW, Agroscope — used under public-sector information principles. Server: Apache-2.0 Ansvar Systems.',
|
|
28
|
+
server: 'ch-environmental-compliance-mcp',
|
|
29
|
+
version: '0.1.0',
|
|
30
|
+
...overrides,
|
|
31
|
+
};
|
|
32
|
+
}
|