@kya-os/create-mcpi-app 1.7.42-canary.6 ā 1.7.42-canary.61
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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test$colon$coverage.log +216 -214
- package/.turbo/turbo-test.log +28 -96
- package/dist/helpers/fetch-cloudflare-mcpi-template.d.ts +17 -6
- package/dist/helpers/fetch-cloudflare-mcpi-template.d.ts.map +1 -1
- package/dist/helpers/fetch-cloudflare-mcpi-template.js +571 -1075
- package/dist/helpers/fetch-cloudflare-mcpi-template.js.map +1 -1
- package/dist/index.js +11 -1
- package/dist/index.js.map +1 -1
- package/package.json +31 -65
|
@@ -1,616 +1,125 @@
|
|
|
1
1
|
import fs from "fs-extra";
|
|
2
2
|
import path from "path";
|
|
3
3
|
import chalk from "chalk";
|
|
4
|
+
import { spawn } from "child_process";
|
|
4
5
|
import { generateIdentity } from "./generate-identity.js";
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
* Uses McpAgent from agents/mcp for MCP protocol support
|
|
8
|
-
*/
|
|
9
|
-
export async function fetchCloudflareMcpiTemplate(projectPath, options = {}) {
|
|
10
|
-
const { packageManager = "npm", projectName = path.basename(projectPath), apikey, projectId, skipIdentity = false, } = options;
|
|
11
|
-
// Sanitize project name for class names
|
|
12
|
-
let className = projectName
|
|
13
|
-
.replace(/[^a-zA-Z0-9]/g, "")
|
|
14
|
-
.replace(/^[0-9]/, "_$&");
|
|
15
|
-
// Fallback to prevent empty class names
|
|
16
|
-
if (!className || className.length === 0) {
|
|
17
|
-
className = "Project";
|
|
18
|
-
}
|
|
19
|
-
const pascalClassName = className.charAt(0).toUpperCase() + className.slice(1);
|
|
20
|
-
// Sanitize project name for wrangler.toml (alphanumeric, lowercase, dashes only)
|
|
21
|
-
let wranglerName = projectName
|
|
22
|
-
.toLowerCase()
|
|
23
|
-
.replace(/[^a-z0-9-]/g, "-") // Replace invalid chars with dashes
|
|
24
|
-
.replace(/-+/g, "-") // Replace multiple dashes with single dash
|
|
25
|
-
.replace(/^-|-$/g, ""); // Remove leading/trailing dashes
|
|
26
|
-
// Fallback to prevent empty wrangler names
|
|
27
|
-
if (!wranglerName || wranglerName.length === 0) {
|
|
28
|
-
wranglerName = "worker";
|
|
29
|
-
}
|
|
30
|
-
try {
|
|
31
|
-
console.log(chalk.blue("š¦ Setting up Cloudflare Worker MCP server..."));
|
|
32
|
-
// Create package.json
|
|
33
|
-
const packageJson = {
|
|
34
|
-
name: projectName,
|
|
35
|
-
version: "0.1.0",
|
|
36
|
-
private: true,
|
|
37
|
-
scripts: {
|
|
38
|
-
setup: "node scripts/setup.js",
|
|
39
|
-
postinstall: "npm run setup",
|
|
40
|
-
deploy: "wrangler deploy",
|
|
41
|
-
dev: "wrangler dev",
|
|
42
|
-
start: "wrangler dev",
|
|
43
|
-
"kv:create": "npm run kv:create-nonce && npm run kv:create-proof && npm run kv:create-identity && npm run kv:create-delegation && npm run kv:create-tool-protection",
|
|
44
|
-
"kv:create-nonce": `wrangler kv namespace create ${className.toUpperCase()}_NONCE_CACHE`,
|
|
45
|
-
"kv:create-proof": `wrangler kv namespace create ${className.toUpperCase()}_PROOF_ARCHIVE`,
|
|
46
|
-
"kv:create-identity": `wrangler kv namespace create ${className.toUpperCase()}_IDENTITY_STORAGE`,
|
|
47
|
-
"kv:create-delegation": `wrangler kv namespace create ${className.toUpperCase()}_DELEGATION_STORAGE`,
|
|
48
|
-
"kv:create-tool-protection": `wrangler kv namespace create ${className.toUpperCase()}_TOOL_PROTECTION_KV`,
|
|
49
|
-
"kv:list": "wrangler kv namespace list | grep -E '(NONCE|PROOF|IDENTITY|DELEGATION|TOOL_PROTECTION|MCPI)' || wrangler kv namespace list",
|
|
50
|
-
"kv:keys-nonce": `wrangler kv key list --binding=${className.toUpperCase()}_NONCE_CACHE`,
|
|
51
|
-
"kv:keys-proof": `wrangler kv key list --binding=${className.toUpperCase()}_PROOF_ARCHIVE`,
|
|
52
|
-
"kv:keys-identity": `wrangler kv key list --binding=${className.toUpperCase()}_IDENTITY_STORAGE`,
|
|
53
|
-
"kv:keys-delegation": `wrangler kv key list --binding=${className.toUpperCase()}_DELEGATION_STORAGE`,
|
|
54
|
-
"kv:keys-tool-protection": `wrangler kv key list --binding=${className.toUpperCase()}_TOOL_PROTECTION_KV`,
|
|
55
|
-
"kv:delete-nonce": `wrangler kv namespace delete --binding=${className.toUpperCase()}_NONCE_CACHE`,
|
|
56
|
-
"kv:delete-proof": `wrangler kv namespace delete --binding=${className.toUpperCase()}_PROOF_ARCHIVE`,
|
|
57
|
-
"kv:delete-identity": `wrangler kv namespace delete --binding=${className.toUpperCase()}_IDENTITY_STORAGE`,
|
|
58
|
-
"kv:delete-delegation": `wrangler kv namespace delete --binding=${className.toUpperCase()}_DELEGATION_STORAGE`,
|
|
59
|
-
"kv:delete-tool-protection": `wrangler kv namespace delete --binding=${className.toUpperCase()}_TOOL_PROTECTION_KV`,
|
|
60
|
-
"kv:delete": "npm run kv:delete-nonce && npm run kv:delete-proof && npm run kv:delete-identity && npm run kv:delete-delegation && npm run kv:delete-tool-protection",
|
|
61
|
-
"kv:reset": "npm run kv:delete && npm run kv:create",
|
|
62
|
-
"kv:setup": "echo 'KV Commands: kv:create (create all), kv:list (list all), kv:keys-* (view keys), kv:delete (delete all), kv:reset (delete+recreate)'",
|
|
63
|
-
"cf-typegen": "wrangler types",
|
|
64
|
-
"type-check": "tsc --noEmit",
|
|
65
|
-
test: "vitest",
|
|
66
|
-
"test:watch": "vitest --watch",
|
|
67
|
-
"test:coverage": "vitest run --coverage",
|
|
68
|
-
},
|
|
69
|
-
dependencies: {
|
|
70
|
-
"@kya-os/contracts": "^1.5.2-canary.5",
|
|
71
|
-
"@kya-os/mcp-i-cloudflare": "1.5.1-canary.5",
|
|
72
|
-
"@modelcontextprotocol/sdk": "^1.19.1",
|
|
73
|
-
agents: "^0.2.21", // Use latest version - constructor now only accepts 2 parameters
|
|
74
|
-
hono: "^4.9.10",
|
|
75
|
-
zod: "^3.25.76",
|
|
76
|
-
},
|
|
77
|
-
devDependencies: {
|
|
78
|
-
"@cloudflare/workers-types": "^4.20251109.0",
|
|
79
|
-
"@kya-os/create-mcpi-app": "^1.7.23",
|
|
80
|
-
"@vitest/coverage-v8": "^3.2.4",
|
|
81
|
-
miniflare: "^3.0.0",
|
|
82
|
-
typescript: "^5.6.2",
|
|
83
|
-
vitest: "^3.2.4",
|
|
84
|
-
wrangler: "^4.42.2",
|
|
85
|
-
},
|
|
86
|
-
};
|
|
87
|
-
fs.ensureDirSync(projectPath); // Ensure directory exists before writing
|
|
88
|
-
fs.writeJsonSync(path.join(projectPath, "package.json"), packageJson, {
|
|
89
|
-
spaces: 2,
|
|
90
|
-
});
|
|
91
|
-
// Create src directory and tools
|
|
92
|
-
const srcDir = path.join(projectPath, "src");
|
|
93
|
-
const toolsDir = path.join(srcDir, "tools");
|
|
94
|
-
fs.ensureDirSync(toolsDir);
|
|
95
|
-
// Create scripts directory
|
|
96
|
-
const scriptsDir = path.join(projectPath, "scripts");
|
|
97
|
-
fs.ensureDirSync(scriptsDir);
|
|
98
|
-
// Create setup.js automation script
|
|
99
|
-
const setupScriptContent = `#!/usr/bin/env node
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Automated Setup Script for ${projectName}
|
|
7
|
+
* Fetches the Cloudflare MCP-I template
|
|
103
8
|
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
9
|
+
* Generates a complete project structure:
|
|
10
|
+
* - package.json with all scripts
|
|
11
|
+
* - wrangler.toml with all KV namespaces configured
|
|
12
|
+
* - .dev.vars with all secrets
|
|
13
|
+
* - src/index.ts
|
|
14
|
+
* - src/agent.ts
|
|
15
|
+
* - src/tools/greet.ts
|
|
16
|
+
* - src/mcpi-runtime-config.ts
|
|
17
|
+
* - scripts/setup.js for KV namespace creation and key regeneration
|
|
18
|
+
* - Automatically runs setup to create KV namespaces
|
|
110
19
|
*/
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
// Colors for terminal output
|
|
123
|
-
const colors = {
|
|
124
|
-
reset: '\\x1b[0m',
|
|
125
|
-
bright: '\\x1b[1m',
|
|
126
|
-
green: '\\x1b[32m',
|
|
127
|
-
yellow: '\\x1b[33m',
|
|
128
|
-
blue: '\\x1b[36m',
|
|
129
|
-
red: '\\x1b[31m'
|
|
130
|
-
};
|
|
131
|
-
|
|
132
|
-
function log(message, color = colors.reset) {
|
|
133
|
-
console.log(color + message + colors.reset);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
function skipToPostKVSetup() {
|
|
137
|
-
// Skip KV creation but continue with other setup steps
|
|
138
|
-
const devVarsPath = path.join(__dirname, '..', '.dev.vars');
|
|
139
|
-
const devVarsExamplePath = path.join(__dirname, '..', '.dev.vars.example');
|
|
140
|
-
|
|
141
|
-
// Create .dev.vars from example if it doesn't exist
|
|
142
|
-
if (!fs.existsSync(devVarsPath) && fs.existsSync(devVarsExamplePath)) {
|
|
143
|
-
log('\\nš Creating .dev.vars from example...', colors.blue);
|
|
144
|
-
fs.copyFileSync(devVarsExamplePath, devVarsPath);
|
|
145
|
-
log('ā
Created .dev.vars - Please update with your values', colors.green);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// Check if identity needs to be generated
|
|
149
|
-
if (fs.existsSync(devVarsPath)) {
|
|
150
|
-
const devVarsContent = fs.readFileSync(devVarsPath, 'utf-8');
|
|
151
|
-
if (devVarsContent.includes('your-private-key-here')) {
|
|
152
|
-
log('\\nš Generating agent identity...', colors.blue);
|
|
153
|
-
try {
|
|
154
|
-
execSync('npx @kya-os/create-mcpi-app regenerate-identity', { stdio: 'inherit' });
|
|
155
|
-
log('ā
Identity generated successfully', colors.green);
|
|
156
|
-
} catch {
|
|
157
|
-
log('ā ļø Could not generate identity automatically. Run: npx @kya-os/create-mcpi-app regenerate-identity', colors.yellow);
|
|
158
|
-
}
|
|
20
|
+
export async function fetchCloudflareMcpiTemplate(targetDir, options) {
|
|
21
|
+
// Handle legacy string argument (projectName) for backward compatibility
|
|
22
|
+
const opts = typeof options === "string"
|
|
23
|
+
? { packageManager: "npm", projectName: options }
|
|
24
|
+
: options;
|
|
25
|
+
// Extract project name from path if not provided
|
|
26
|
+
let projectName = opts.projectName;
|
|
27
|
+
if (!projectName) {
|
|
28
|
+
const pathParts = targetDir.split(path.sep);
|
|
29
|
+
projectName = pathParts[pathParts.length - 1] || "worker";
|
|
159
30
|
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
async function setup() {
|
|
182
|
-
log('\\nš Starting automated setup for ${projectName}...\\n', colors.bright + colors.blue);
|
|
183
|
-
|
|
184
|
-
// 1. Check wrangler installation
|
|
185
|
-
try {
|
|
186
|
-
const wranglerVersion = execSync('wrangler --version', { encoding: 'utf-8' });
|
|
187
|
-
log('ā
Wrangler CLI detected: ' + wranglerVersion.trim(), colors.green);
|
|
188
|
-
} catch {
|
|
189
|
-
log('š¦ Wrangler CLI not found. Installing...', colors.yellow);
|
|
190
|
-
try {
|
|
191
|
-
execSync('npm install -g wrangler', { stdio: 'inherit' });
|
|
192
|
-
log('ā
Wrangler CLI installed successfully', colors.green);
|
|
193
|
-
} catch (error) {
|
|
194
|
-
log('ā Failed to install Wrangler. Please install manually: npm install -g wrangler', colors.red);
|
|
195
|
-
process.exit(1);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// 2. Check if user is logged in to Cloudflare
|
|
200
|
-
try {
|
|
201
|
-
execSync('wrangler whoami', { encoding: 'utf-8' });
|
|
202
|
-
log('ā
Logged in to Cloudflare', colors.green);
|
|
203
|
-
} catch {
|
|
204
|
-
log('š Please log in to Cloudflare:', colors.yellow);
|
|
205
|
-
try {
|
|
206
|
-
execSync('wrangler login', { stdio: 'inherit' });
|
|
207
|
-
} catch (error) {
|
|
208
|
-
log('ā Login failed. Please run: wrangler login', colors.red);
|
|
209
|
-
process.exit(1);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// 2.5. Set up wrangler.toml path for later use
|
|
214
|
-
const wranglerTomlPath = path.join(__dirname, '..', 'wrangler.toml');
|
|
215
|
-
let wranglerContent = '';
|
|
216
|
-
|
|
217
|
-
try {
|
|
218
|
-
wranglerContent = fs.readFileSync(wranglerTomlPath, 'utf-8');
|
|
219
|
-
} catch (error) {
|
|
220
|
-
log('ā ļø Could not read wrangler.toml', colors.yellow);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// 3. Create KV namespaces
|
|
224
|
-
log('\\nš Creating KV namespaces...\\n', colors.bright);
|
|
225
|
-
|
|
226
|
-
const namespaces = [
|
|
227
|
-
{ binding: '${className.toUpperCase()}_NONCE_CACHE', name: 'Nonce Cache', purpose: 'Replay attack prevention' },
|
|
228
|
-
{ binding: '${className.toUpperCase()}_PROOF_ARCHIVE', name: 'Proof Archive', purpose: 'Cryptographic proof storage' },
|
|
229
|
-
{ binding: '${className.toUpperCase()}_IDENTITY_STORAGE', name: 'Identity Storage', purpose: 'Agent identity persistence' },
|
|
230
|
-
{ binding: '${className.toUpperCase()}_DELEGATION_STORAGE', name: 'Delegation Storage', purpose: 'OAuth token storage' },
|
|
231
|
-
{ binding: '${className.toUpperCase()}_TOOL_PROTECTION_KV', name: 'Tool Protection', purpose: 'Permission caching' }
|
|
232
|
-
];
|
|
233
|
-
|
|
234
|
-
const kvIds = {};
|
|
235
|
-
let multipleAccountsDetected = false;
|
|
236
|
-
|
|
237
|
-
for (const ns of namespaces) {
|
|
238
|
-
// If we already detected multiple accounts, skip remaining namespaces
|
|
239
|
-
if (multipleAccountsDetected) {
|
|
240
|
-
break;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
log(\`Creating \${ns.name} (\${ns.purpose})...\`, colors.blue);
|
|
244
|
-
|
|
245
|
-
// First, check if namespace already exists
|
|
246
|
-
let existingNamespace = null;
|
|
247
|
-
try {
|
|
248
|
-
const listOutput = execSync('wrangler kv namespace list', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
249
|
-
|
|
250
|
-
try {
|
|
251
|
-
const allNamespaces = JSON.parse(listOutput);
|
|
252
|
-
existingNamespace = allNamespaces.find(n => n.title === ns.binding);
|
|
253
|
-
} catch (parseError) {
|
|
254
|
-
// Fallback to regex if JSON parsing fails
|
|
255
|
-
const existingMatch = listOutput.match(new RegExp(\`"title":\\s*"\${ns.binding}"[^}]*"id":\\s*"([^"]+)"\`));
|
|
256
|
-
if (existingMatch && existingMatch[1]) {
|
|
257
|
-
existingNamespace = { id: existingMatch[1], title: ns.binding };
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
} catch (listError) {
|
|
261
|
-
// If we can't list namespaces, continue to try creating
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
if (existingNamespace && existingNamespace.id) {
|
|
265
|
-
kvIds[ns.binding] = existingNamespace.id;
|
|
266
|
-
log(\` ā
Using existing namespace with ID: \${existingNamespace.id}\`, colors.green);
|
|
267
|
-
continue;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// Namespace doesn't exist, try to create it
|
|
271
|
-
try {
|
|
272
|
-
// Suppress stderr to avoid noisy error messages
|
|
273
|
-
const output = execSync(\`wrangler kv namespace create "\${ns.binding}"\`, {
|
|
274
|
-
encoding: 'utf-8',
|
|
275
|
-
stdio: ['pipe', 'pipe', 'pipe']
|
|
276
|
-
});
|
|
277
|
-
|
|
278
|
-
// Extract the ID from output
|
|
279
|
-
const idMatch = output.match(/id = "([^"]+)"/);
|
|
280
|
-
|
|
281
|
-
if (idMatch && idMatch[1]) {
|
|
282
|
-
kvIds[ns.binding] = idMatch[1];
|
|
283
|
-
log(\` ā
Created with ID: \${idMatch[1]}\`, colors.green);
|
|
284
|
-
} else {
|
|
285
|
-
log(\` ā ļø Created but could not extract ID. Checking existing namespaces...\`, colors.yellow);
|
|
286
|
-
// Fallback: try to find it in the list
|
|
287
|
-
const listOutput = execSync('wrangler kv namespace list', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
288
|
-
try {
|
|
289
|
-
const allNamespaces = JSON.parse(listOutput);
|
|
290
|
-
const found = allNamespaces.find(n => n.title === ns.binding);
|
|
291
|
-
if (found && found.id) {
|
|
292
|
-
kvIds[ns.binding] = found.id;
|
|
293
|
-
log(\` ā
Found ID: \${found.id}\`, colors.green);
|
|
294
|
-
}
|
|
295
|
-
} catch {
|
|
296
|
-
// Ignore parse errors
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
} catch (error) {
|
|
300
|
-
const errorMessage = error.message || error.toString();
|
|
301
|
-
const errorOutput = error.stdout || error.stderr || '';
|
|
302
|
-
|
|
303
|
-
// Check if this is a multiple accounts error
|
|
304
|
-
if (errorMessage.includes('More than one account') || errorMessage.includes('multiple accounts') || errorOutput.includes('More than one account')) {
|
|
305
|
-
multipleAccountsDetected = true;
|
|
306
|
-
log('\\nā ļø Multiple Cloudflare accounts detected!\\n', colors.yellow);
|
|
307
|
-
log('Wrangler cannot automatically select an account in non-interactive mode.\\n', colors.yellow);
|
|
308
|
-
log('To fix this, choose one of these options:\\n', colors.bright);
|
|
309
|
-
log('Option 1: Set environment variable (recommended):', colors.blue);
|
|
310
|
-
log(' export CLOUDFLARE_ACCOUNT_ID=your-account-id', colors.reset);
|
|
311
|
-
log(' npm run setup\\n', colors.reset);
|
|
312
|
-
log('Option 2: Add to wrangler.toml (permanent):', colors.blue);
|
|
313
|
-
log(' Edit wrangler.toml and add:', colors.reset);
|
|
314
|
-
log(' account_id = "your-account-id"\\n', colors.reset);
|
|
315
|
-
log('Find your account IDs in the error above or run:', colors.blue);
|
|
316
|
-
log(' wrangler whoami\\n', colors.reset);
|
|
317
|
-
log('āļø Skipping remaining KV namespace creation.', colors.yellow);
|
|
318
|
-
log('After setting account_id, run: npm run setup\\n', colors.yellow);
|
|
319
|
-
break;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// Check if namespace already exists (common case - suppress noisy error)
|
|
323
|
-
if (errorMessage.includes('already exists') || errorOutput.includes('already exists') || errorOutput.includes('code: 10014')) {
|
|
324
|
-
// Try to get the existing namespace ID
|
|
325
|
-
try {
|
|
326
|
-
const listOutput = execSync('wrangler kv namespace list', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
327
|
-
|
|
328
|
-
try {
|
|
329
|
-
const allNamespaces = JSON.parse(listOutput);
|
|
330
|
-
const found = allNamespaces.find(n => n.title === ns.binding);
|
|
331
|
-
|
|
332
|
-
if (found && found.id) {
|
|
333
|
-
kvIds[ns.binding] = found.id;
|
|
334
|
-
log(\` ā
Using existing namespace with ID: \${found.id}\`, colors.green);
|
|
335
|
-
} else {
|
|
336
|
-
log(\` ā ļø Namespace exists but could not find ID. You may need to add it manually.\`, colors.yellow);
|
|
337
|
-
}
|
|
338
|
-
} catch (parseError) {
|
|
339
|
-
// Fallback to regex
|
|
340
|
-
const existingMatch = listOutput.match(new RegExp(\`"title":\\s*"\${ns.binding}"[^}]*"id":\\s*"([^"]+)"\`));
|
|
341
|
-
if (existingMatch && existingMatch[1]) {
|
|
342
|
-
kvIds[ns.binding] = existingMatch[1];
|
|
343
|
-
log(\` ā
Using existing namespace with ID: \${existingMatch[1]}\`, colors.green);
|
|
344
|
-
} else {
|
|
345
|
-
log(\` ā ļø Namespace exists but could not find ID. You may need to add it manually.\`, colors.yellow);
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
} catch (listError) {
|
|
349
|
-
log(\` ā ļø Namespace may already exist. Run 'wrangler kv namespace list' to verify.\`, colors.yellow);
|
|
350
|
-
}
|
|
351
|
-
} else {
|
|
352
|
-
// Some other error occurred
|
|
353
|
-
log(\` ā Failed to create \${ns.binding}\`, colors.red);
|
|
354
|
-
log(\` Error: \${errorMessage}\`, colors.red);
|
|
355
|
-
}
|
|
31
|
+
const { apikey, projectId, packageManager, skipCommands } = opts;
|
|
32
|
+
const projectNameUpper = projectName.toUpperCase().replace(/-/g, "_");
|
|
33
|
+
console.log(chalk.blue(`\nšļø Generating Cloudflare MCP-I project: ${projectName}...`));
|
|
34
|
+
// 1. Create directory structure
|
|
35
|
+
await fs.ensureDir(path.join(targetDir, "src"));
|
|
36
|
+
await fs.ensureDir(path.join(targetDir, "src/tools"));
|
|
37
|
+
await fs.ensureDir(path.join(targetDir, "scripts"));
|
|
38
|
+
// 2. Generate Identity (Keys & DID)
|
|
39
|
+
let identity;
|
|
40
|
+
if (opts.skipIdentity) {
|
|
41
|
+
// Use a mock identity when skipping generation
|
|
42
|
+
identity = {
|
|
43
|
+
did: "did:key:zTestMockIdentity",
|
|
44
|
+
kid: "did:key:zTestMockIdentity#key-1",
|
|
45
|
+
privateKey: "mock-private-key",
|
|
46
|
+
publicKey: "mock-public-key",
|
|
47
|
+
createdAt: new Date().toISOString(),
|
|
48
|
+
type: "development",
|
|
49
|
+
};
|
|
356
50
|
}
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
if (multipleAccountsDetected) {
|
|
361
|
-
return skipToPostKVSetup();
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// 4. Update wrangler.toml with KV IDs
|
|
365
|
-
if (Object.keys(kvIds).length > 0) {
|
|
366
|
-
log('\\nš Updating wrangler.toml with KV namespace IDs...\\n', colors.bright);
|
|
367
|
-
|
|
368
|
-
try {
|
|
369
|
-
wranglerContent = fs.readFileSync(wranglerTomlPath, 'utf-8');
|
|
370
|
-
let updatedCount = 0;
|
|
371
|
-
|
|
372
|
-
for (const [binding, id] of Object.entries(kvIds)) {
|
|
373
|
-
// Match pattern: binding = "BINDING_NAME"\\nid = "anything" (including placeholders)
|
|
374
|
-
const pattern = new RegExp(\`(binding = "\${binding}")\\\\s*\\\\nid = "[^"]*"\`, 'g');
|
|
375
|
-
const replacement = \`$1\\nid = "\${id}"\`;
|
|
376
|
-
|
|
377
|
-
const newContent = wranglerContent.replace(pattern, replacement);
|
|
378
|
-
if (newContent !== wranglerContent) {
|
|
379
|
-
updatedCount++;
|
|
380
|
-
log(\` ā
Updated \${binding} with ID: \${id}\`, colors.green);
|
|
381
|
-
}
|
|
382
|
-
wranglerContent = newContent;
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
fs.writeFileSync(wranglerTomlPath, wranglerContent);
|
|
386
|
-
log(\`\\nā
Updated \${updatedCount} namespace ID(s) in wrangler.toml\`, colors.green);
|
|
387
|
-
|
|
388
|
-
// Show remaining placeholder IDs if any
|
|
389
|
-
const placeholderMatches = wranglerContent.match(/binding = "[^"]+"\\s*\\nid = "your_[^"]+"/g);
|
|
390
|
-
if (placeholderMatches) {
|
|
391
|
-
log('\\nā ļø Some namespace IDs still have placeholders:', colors.yellow);
|
|
392
|
-
placeholderMatches.forEach(match => {
|
|
393
|
-
const bindingMatch = match.match(/binding = "([^"]+)"/);
|
|
394
|
-
if (bindingMatch) {
|
|
395
|
-
log(\` - \${bindingMatch[1]}\`, colors.yellow);
|
|
396
|
-
}
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
} catch (error) {
|
|
400
|
-
log(\`ā Failed to update wrangler.toml: \${error.message}\`, colors.red);
|
|
51
|
+
else {
|
|
52
|
+
console.log(chalk.blue("š Generating cryptographic identity..."));
|
|
53
|
+
identity = await generateIdentity();
|
|
401
54
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
log(' npm run dev - Start local development server');
|
|
435
|
-
log(' npm run deploy - Deploy to Cloudflare Workers');
|
|
436
|
-
log(' npm run kv:list - List all KV namespaces');
|
|
437
|
-
log(' wrangler secret put <KEY> - Set production secrets');
|
|
438
|
-
log('\\nFor more information, see the README.md file.\\n');
|
|
439
|
-
|
|
440
|
-
rl.close();
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
// Handle errors gracefully
|
|
444
|
-
process.on('unhandledRejection', (error) => {
|
|
445
|
-
log(\`\\nā Setup failed: \${error.message}\`, colors.red);
|
|
446
|
-
process.exit(1);
|
|
447
|
-
});
|
|
448
|
-
|
|
449
|
-
// Run the setup
|
|
450
|
-
setup().catch((error) => {
|
|
451
|
-
log(\`\\nā Setup failed: \${error.message}\`, colors.red);
|
|
452
|
-
process.exit(1);
|
|
453
|
-
});
|
|
454
|
-
`;
|
|
455
|
-
fs.writeFileSync(path.join(scriptsDir, "setup.js"), setupScriptContent);
|
|
456
|
-
// Make setup script executable
|
|
457
|
-
if (process.platform !== "win32") {
|
|
458
|
-
fs.chmodSync(path.join(scriptsDir, "setup.js"), "755");
|
|
459
|
-
}
|
|
460
|
-
// Note: Tests directory is not created by default
|
|
461
|
-
// Users can add their own tests as needed
|
|
462
|
-
// Create greet tool
|
|
463
|
-
const greetToolContent = `import { z } from "zod";
|
|
464
|
-
|
|
465
|
-
/**
|
|
466
|
-
* Greet Tool - Example MCP tool with AgentShield integration
|
|
467
|
-
*
|
|
468
|
-
* This tool demonstrates proper scopeId configuration for tool auto-discovery.
|
|
469
|
-
*
|
|
470
|
-
* Configure the corresponding scope in mcpi-runtime-config.ts:
|
|
471
|
-
* \`\`\`typescript
|
|
472
|
-
* toolProtections: {
|
|
473
|
-
* greet: {
|
|
474
|
-
* requiresDelegation: false,
|
|
475
|
-
* requiredScopes: ["greet:execute"], // ā This becomes the scopeId in proofs
|
|
476
|
-
* }
|
|
477
|
-
* }
|
|
478
|
-
* \`\`\`
|
|
479
|
-
*
|
|
480
|
-
* The scopeId format is "toolName:action":
|
|
481
|
-
* - Tool name: "greet" (extracted before the ":")
|
|
482
|
-
* - Action: "execute" (extracted after the ":")
|
|
483
|
-
* - Risk level: Auto-determined from action keyword (execute = high)
|
|
484
|
-
*
|
|
485
|
-
* Other scopeId examples:
|
|
486
|
-
* - "files:read" ā Medium risk
|
|
487
|
-
* - "files:write" ā High risk
|
|
488
|
-
* - "database:delete" ā Critical risk
|
|
489
|
-
*/
|
|
490
|
-
export const greetTool = {
|
|
491
|
-
name: "greet",
|
|
492
|
-
description: "Greet a user by name",
|
|
493
|
-
inputSchema: z.object({
|
|
494
|
-
name: z.string().describe("The name of the user to greet")
|
|
495
|
-
}),
|
|
496
|
-
handler: async ({ name }: { name: string }) => {
|
|
497
|
-
return {
|
|
498
|
-
content: [
|
|
499
|
-
{
|
|
500
|
-
type: "text" as const,
|
|
501
|
-
text: \`Hello, \${name}! Welcome to your Cloudflare MCP server.\`
|
|
502
|
-
}
|
|
503
|
-
]
|
|
55
|
+
// 3. Create package.json with all scripts
|
|
56
|
+
const packageJson = {
|
|
57
|
+
name: projectName,
|
|
58
|
+
version: "0.1.0",
|
|
59
|
+
private: true,
|
|
60
|
+
scripts: {
|
|
61
|
+
deploy: "wrangler deploy",
|
|
62
|
+
dev: "wrangler dev",
|
|
63
|
+
start: "wrangler dev",
|
|
64
|
+
test: "vitest",
|
|
65
|
+
"cf-typegen": "wrangler types",
|
|
66
|
+
setup: "node scripts/setup.js",
|
|
67
|
+
"kv:create-nonce": `wrangler kv:namespace create ${projectNameUpper}_NONCE_CACHE`,
|
|
68
|
+
"kv:create-proof": `wrangler kv:namespace create ${projectNameUpper}_PROOF_ARCHIVE`,
|
|
69
|
+
"kv:create-identity": `wrangler kv:namespace create ${projectNameUpper}_IDENTITY_STORAGE`,
|
|
70
|
+
"kv:create-delegation": `wrangler kv:namespace create ${projectNameUpper}_DELEGATION_STORAGE`,
|
|
71
|
+
"kv:create-tool-protection": `wrangler kv:namespace create ${projectNameUpper}_TOOL_PROTECTION_KV`,
|
|
72
|
+
},
|
|
73
|
+
dependencies: {
|
|
74
|
+
"@kya-os/mcp-i-cloudflare": "1.5.8-canary.60",
|
|
75
|
+
"@modelcontextprotocol/sdk": "0.6.0",
|
|
76
|
+
agents: "0.2.21",
|
|
77
|
+
hono: "4.6.3",
|
|
78
|
+
},
|
|
79
|
+
devDependencies: {
|
|
80
|
+
"@cloudflare/vitest-pool-workers": "0.5.2",
|
|
81
|
+
"@cloudflare/workers-types": "4.20240925.0",
|
|
82
|
+
"@types/node": "20.8.3",
|
|
83
|
+
typescript: "5.5.2",
|
|
84
|
+
vitest: "2.0.5",
|
|
85
|
+
wrangler: "3.78.12",
|
|
86
|
+
},
|
|
504
87
|
};
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
/**
|
|
515
|
-
* Runtime configuration for MCP-I server
|
|
516
|
-
*
|
|
517
|
-
* This file configures runtime features like proof submission to AgentShield,
|
|
518
|
-
* delegation verification, and audit logging.
|
|
519
|
-
*
|
|
520
|
-
* Environment variables are automatically injected from wrangler.toml (Cloudflare)
|
|
521
|
-
* or .env (Node.js). Configure them there:
|
|
522
|
-
* - AGENTSHIELD_API_URL: AgentShield API base URL
|
|
523
|
-
* - AGENTSHIELD_API_KEY: Your AgentShield API key
|
|
524
|
-
* - AGENTSHIELD_PROJECT_ID: Your AgentShield project ID (optional but recommended)
|
|
525
|
-
* - MCPI_ENV: "development" or "production"
|
|
526
|
-
*
|
|
527
|
-
* Tool Protection:
|
|
528
|
-
* - Automatically enabled if AGENTSHIELD_API_KEY and TOOL_PROTECTION_KV are set
|
|
529
|
-
* - Fetches tool protection config from AgentShield API by project ID
|
|
530
|
-
* - Caches config for 5 minutes to minimize API calls
|
|
531
|
-
* - Falls back to local config if API is unavailable
|
|
532
|
-
* - Configure delegation requirements in AgentShield dashboard
|
|
533
|
-
*/
|
|
534
|
-
export function getRuntimeConfig(env: CloudflareEnv): CloudflareRuntimeConfig {
|
|
535
|
-
return defineConfig({
|
|
536
|
-
// Only specify overrides - defaults are handled automatically
|
|
537
|
-
vars: {
|
|
538
|
-
ENVIRONMENT: env.ENVIRONMENT || env.MCPI_ENV || 'development',
|
|
539
|
-
AGENTSHIELD_API_KEY: env.AGENTSHIELD_API_KEY,
|
|
540
|
-
AGENTSHIELD_API_URL: env.AGENTSHIELD_API_URL,
|
|
541
|
-
},
|
|
542
|
-
// Tool protection is automatically enabled by defineConfig if AGENTSHIELD_API_KEY is present
|
|
543
|
-
// You can override by explicitly setting toolProtection here
|
|
544
|
-
// Optional: Enable admin endpoints
|
|
545
|
-
admin: {
|
|
546
|
-
enabled: false, // Set to true and provide ADMIN_API_KEY to enable
|
|
547
|
-
apiKey: env.ADMIN_API_KEY,
|
|
548
|
-
},
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
`;
|
|
552
|
-
fs.writeFileSync(path.join(srcDir, "mcpi-runtime-config.ts"), runtimeConfigContent);
|
|
553
|
-
// Create main index.ts using MCPICloudflareServer
|
|
554
|
-
const indexContent = `import { MCPICloudflareAgent, createMCPIApp, type PrefixedCloudflareEnv } from "@kya-os/mcp-i-cloudflare";
|
|
555
|
-
import { greetTool } from "./tools/greet";
|
|
556
|
-
import { getRuntimeConfig } from "./mcpi-runtime-config";
|
|
557
|
-
|
|
558
|
-
/**
|
|
559
|
-
* Extended CloudflareEnv with prefixed KV bindings for multi-agent deployments
|
|
560
|
-
*/
|
|
561
|
-
interface MyPrefixedCloudflareEnv extends PrefixedCloudflareEnv {
|
|
562
|
-
${className.toUpperCase()}_NONCE_CACHE?: KVNamespace;
|
|
563
|
-
${className.toUpperCase()}_PROOF_ARCHIVE?: KVNamespace;
|
|
564
|
-
${className.toUpperCase()}_IDENTITY_STORAGE?: KVNamespace;
|
|
565
|
-
${className.toUpperCase()}_DELEGATION_STORAGE?: KVNamespace;
|
|
566
|
-
${className.toUpperCase()}_TOOL_PROTECTION_KV?: KVNamespace;
|
|
567
|
-
}
|
|
88
|
+
await fs.writeJson(path.join(targetDir, "package.json"), packageJson, {
|
|
89
|
+
spaces: 2,
|
|
90
|
+
});
|
|
91
|
+
// 4. Create .dev.vars with ALL secrets
|
|
92
|
+
const devVarsContent = `# Secrets for local development
|
|
93
|
+
# Generated by create-mcpi-app
|
|
94
|
+
|
|
95
|
+
# Agent Identity (DO NOT COMMIT THIS FILE)
|
|
96
|
+
MCP_IDENTITY_PRIVATE_KEY="${identity.privateKey}"
|
|
568
97
|
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
* All framework complexity (runtime initialization, proof generation, etc.) is handled automatically.
|
|
572
|
-
*/
|
|
573
|
-
export class ${pascalClassName}MCP extends MCPICloudflareAgent {
|
|
574
|
-
async registerTools() {
|
|
575
|
-
// Register your custom tools - proofs are generated automatically
|
|
576
|
-
this.server.tool(
|
|
577
|
-
greetTool.name,
|
|
578
|
-
greetTool.description,
|
|
579
|
-
greetTool.inputSchema.shape,
|
|
580
|
-
async (args: { name: string }) => {
|
|
581
|
-
return this.executeToolWithProof(
|
|
582
|
-
greetTool.name,
|
|
583
|
-
args,
|
|
584
|
-
greetTool.handler
|
|
585
|
-
);
|
|
586
|
-
}
|
|
587
|
-
);
|
|
588
|
-
}
|
|
589
|
-
}
|
|
98
|
+
# AgentShield Configuration
|
|
99
|
+
${apikey ? `AGENTSHIELD_API_KEY="${apikey}"` : '# AGENTSHIELD_API_KEY="sk_YOUR_API_KEY_HERE"'}
|
|
590
100
|
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
agentVersion: "1.0.0",
|
|
596
|
-
envPrefix: "${className.toUpperCase()}",
|
|
597
|
-
getRuntimeConfig,
|
|
598
|
-
});
|
|
101
|
+
# Admin API Key for cache management
|
|
102
|
+
# Uses the same key as AGENTSHIELD_API_KEY for convenience
|
|
103
|
+
# You can change this to a different key if you need separate admin access
|
|
104
|
+
${apikey ? `ADMIN_API_KEY="${apikey}"` : '# ADMIN_API_KEY="sk_YOUR_ADMIN_KEY_HERE"'}
|
|
599
105
|
`;
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
106
|
+
await fs.writeFile(path.join(targetDir, ".dev.vars"), devVarsContent);
|
|
107
|
+
// 5. Create wrangler.toml with all KV namespaces (placeholders initially)
|
|
108
|
+
const wranglerToml = `#:schema node_modules/wrangler/config-schema.json
|
|
109
|
+
name = "${projectName}"
|
|
603
110
|
main = "src/index.ts"
|
|
604
|
-
compatibility_date = "
|
|
111
|
+
compatibility_date = "2024-09-25"
|
|
605
112
|
compatibility_flags = ["nodejs_compat"]
|
|
606
113
|
|
|
114
|
+
# Durable Object binding for MCP Agent state
|
|
607
115
|
[[durable_objects.bindings]]
|
|
608
116
|
name = "MCP_OBJECT"
|
|
609
|
-
class_name = "${
|
|
117
|
+
class_name = "${toPascalCase(projectName)}MCP"
|
|
610
118
|
|
|
611
119
|
[[migrations]]
|
|
612
120
|
tag = "v1"
|
|
613
|
-
new_sqlite_classes
|
|
121
|
+
# Use new_sqlite_classes instead of new_classes - required by agents package for SQL storage
|
|
122
|
+
new_sqlite_classes = ["${toPascalCase(projectName)}MCP"]
|
|
614
123
|
|
|
615
124
|
# Cron trigger for proof batch queue flushing (OPTIONAL - CURRENTLY DISABLED)
|
|
616
125
|
#
|
|
@@ -639,8 +148,8 @@ new_sqlite_classes = ["${pascalClassName}MCP"]
|
|
|
639
148
|
# This namespace is automatically created by the setup script (npm run setup)
|
|
640
149
|
# If you need to recreate it: npm run kv:create-nonce
|
|
641
150
|
[[kv_namespaces]]
|
|
642
|
-
binding = "${
|
|
643
|
-
id = "
|
|
151
|
+
binding = "${projectNameUpper}_NONCE_CACHE"
|
|
152
|
+
id = "TODO_REPLACE_WITH_ID" # Auto-filled by setup script
|
|
644
153
|
|
|
645
154
|
# KV Namespace for proof archive (RECOMMENDED for auditability)
|
|
646
155
|
#
|
|
@@ -651,8 +160,8 @@ id = "your_nonce_kv_namespace_id" # Auto-filled by setup script
|
|
|
651
160
|
#
|
|
652
161
|
# Note: Comment out if you don't need proof archiving
|
|
653
162
|
[[kv_namespaces]]
|
|
654
|
-
binding = "${
|
|
655
|
-
id = "
|
|
163
|
+
binding = "${projectNameUpper}_PROOF_ARCHIVE"
|
|
164
|
+
id = "TODO_REPLACE_WITH_ID" # Auto-filled by setup script
|
|
656
165
|
|
|
657
166
|
# KV Namespace for identity storage (RECOMMENDED for persistent agent identity)
|
|
658
167
|
#
|
|
@@ -661,8 +170,8 @@ id = "your_proof_kv_namespace_id" # Auto-filled by setup script
|
|
|
661
170
|
# This namespace is automatically created by the setup script (npm run setup)
|
|
662
171
|
# If you need to recreate it: npm run kv:create-identity
|
|
663
172
|
[[kv_namespaces]]
|
|
664
|
-
binding = "${
|
|
665
|
-
id = "
|
|
173
|
+
binding = "${projectNameUpper}_IDENTITY_STORAGE"
|
|
174
|
+
id = "TODO_REPLACE_WITH_ID" # Auto-filled by setup script
|
|
666
175
|
|
|
667
176
|
# KV Namespace for delegation storage (REQUIRED for OAuth/delegation flows)
|
|
668
177
|
#
|
|
@@ -671,10 +180,10 @@ id = "your_identity_kv_namespace_id" # Auto-filled by setup script
|
|
|
671
180
|
# This namespace is automatically created by the setup script (npm run setup)
|
|
672
181
|
# If you need to recreate it: npm run kv:create-delegation
|
|
673
182
|
[[kv_namespaces]]
|
|
674
|
-
binding = "${
|
|
675
|
-
id = "
|
|
183
|
+
binding = "${projectNameUpper}_DELEGATION_STORAGE"
|
|
184
|
+
id = "TODO_REPLACE_WITH_ID" # Auto-filled by setup script
|
|
676
185
|
|
|
677
|
-
# KV Namespace for tool protection config (
|
|
186
|
+
# KV Namespace for tool protection config (ENABLED for dashboard-controlled delegation)
|
|
678
187
|
#
|
|
679
188
|
# š Enables dynamic tool protection configuration from AgentShield dashboard
|
|
680
189
|
# Caches which tools require user delegation based on dashboard toggle switches
|
|
@@ -692,532 +201,519 @@ id = "your_delegation_kv_namespace_id" # Auto-filled by setup script
|
|
|
692
201
|
# Note: This namespace is REQUIRED when using AgentShield API key (--apikey)
|
|
693
202
|
# It will be automatically created by the setup script (npm run setup)
|
|
694
203
|
[[kv_namespaces]]
|
|
695
|
-
binding = "${
|
|
696
|
-
id = "
|
|
204
|
+
binding = "${projectNameUpper}_TOOL_PROTECTION_KV"
|
|
205
|
+
id = "TODO_REPLACE_WITH_ID" # Auto-filled by setup script
|
|
697
206
|
|
|
698
207
|
[vars]
|
|
208
|
+
# Agent DID (public identifier - safe to commit)
|
|
209
|
+
MCP_IDENTITY_AGENT_DID = "${identity.did}"
|
|
210
|
+
|
|
211
|
+
# Public identity key (safe to commit - not sensitive)
|
|
212
|
+
MCP_IDENTITY_PUBLIC_KEY = "${identity.publicKey}"
|
|
213
|
+
|
|
214
|
+
# Private identity key (SECRET - NOT declared here)
|
|
215
|
+
# For local development: Add to .dev.vars file
|
|
216
|
+
# For production: Use wrangler secret put MCP_IDENTITY_PRIVATE_KEY
|
|
217
|
+
|
|
218
|
+
# ALLOWED_ORIGINS for CORS (update for production)
|
|
219
|
+
ALLOWED_ORIGINS = "https://claude.ai,https://app.anthropic.com"
|
|
220
|
+
|
|
221
|
+
# DO routing strategy: "session" for dev, "shard" for production high-load
|
|
222
|
+
DO_ROUTING_STRATEGY = "session"
|
|
223
|
+
DO_SHARD_COUNT = "10" # Number of shards if using shard strategy
|
|
224
|
+
|
|
699
225
|
XMCP_I_TS_SKEW_SEC = "120"
|
|
700
226
|
XMCP_I_SESSION_TTL = "1800"
|
|
701
227
|
|
|
702
228
|
# AgentShield Integration (https://kya.vouched.id)
|
|
703
229
|
AGENTSHIELD_API_URL = "https://kya.vouched.id"
|
|
230
|
+
|
|
704
231
|
# AGENTSHIELD_PROJECT_ID - Your project ID from AgentShield dashboard (e.g., "batman-txh0ae")
|
|
705
232
|
# Required for project-scoped tool protection configuration (recommended)
|
|
706
233
|
# Find it in your dashboard URL: https://kya.vouched.id/dashboard/projects/{PROJECT_ID}
|
|
707
234
|
# Or in your project settings
|
|
708
235
|
# This is not sensitive, so it's safe to keep a value here
|
|
709
|
-
AGENTSHIELD_PROJECT_ID = "${projectId
|
|
236
|
+
${projectId ? `AGENTSHIELD_PROJECT_ID = "${projectId}"` : '# AGENTSHIELD_PROJECT_ID = "your-project-id"'}
|
|
237
|
+
|
|
710
238
|
MCPI_ENV = "development"
|
|
711
239
|
|
|
712
240
|
# Secrets (NOT declared here - see instructions below)
|
|
713
241
|
# For local development: Add secrets to .dev.vars file
|
|
714
242
|
# For production: Use wrangler secret put COMMAND_NAME
|
|
243
|
+
#
|
|
244
|
+
# Required secrets:
|
|
715
245
|
# $ wrangler secret put MCP_IDENTITY_PRIVATE_KEY
|
|
716
|
-
#
|
|
717
|
-
#
|
|
246
|
+
#
|
|
247
|
+
# Optional secrets (recommended for production):
|
|
248
|
+
# $ wrangler secret put AGENTSHIELD_API_KEY # For AgentShield integration
|
|
249
|
+
#
|
|
250
|
+
# Optional secrets (advanced):
|
|
251
|
+
# $ wrangler secret put ADMIN_API_KEY # For cache management endpoints
|
|
252
|
+
# # Falls back to AGENTSHIELD_API_KEY if not set
|
|
253
|
+
#
|
|
718
254
|
# Note: .dev.vars is git-ignored and contains actual secret values for local dev
|
|
719
255
|
|
|
720
256
|
# Optional: MCP Server URL for tool discovery and consent page generation
|
|
721
257
|
# Uncomment to explicitly set your MCP server URL (auto-detected from request origin if not set)
|
|
722
258
|
# IMPORTANT: Use base URL WITHOUT /mcp suffix (e.g., "https://your-worker.workers.dev")
|
|
723
259
|
# The consent pages are at /consent, not /mcp/consent
|
|
724
|
-
# MCP_SERVER_URL = "https
|
|
725
|
-
`;
|
|
726
|
-
fs.writeFileSync(path.join(projectPath, "wrangler.toml"), wranglerContent);
|
|
727
|
-
// Generate persistent identity for Cloudflare Worker
|
|
728
|
-
if (!skipIdentity) {
|
|
729
|
-
console.log(chalk.cyan("š Generating persistent identity..."));
|
|
730
|
-
try {
|
|
731
|
-
const identity = await generateIdentity();
|
|
732
|
-
// Read existing wrangler.toml
|
|
733
|
-
const wranglerPath = path.join(projectPath, "wrangler.toml");
|
|
734
|
-
let wranglerTomlContent = fs.readFileSync(wranglerPath, "utf8");
|
|
735
|
-
// Find [vars] section and add identity environment variables
|
|
736
|
-
// Add ALL identity variables (empty values will be overridden by .dev.vars)
|
|
737
|
-
const varsMatch = wranglerTomlContent.match(/\[vars\]/);
|
|
738
|
-
if (varsMatch) {
|
|
739
|
-
const insertPosition = varsMatch.index + varsMatch[0].length;
|
|
740
|
-
const identityVars = `
|
|
741
|
-
# Agent DID (public identifier - safe to commit)
|
|
742
|
-
MCP_IDENTITY_AGENT_DID = "${identity.did}"
|
|
743
|
-
|
|
744
|
-
# Public identity key (safe to commit - not sensitive)
|
|
745
|
-
MCP_IDENTITY_PUBLIC_KEY = "${identity.publicKey}"
|
|
746
|
-
|
|
747
|
-
# Private identity key (SECRET - NOT declared here)
|
|
748
|
-
# For local development: Add to .dev.vars file
|
|
749
|
-
# For production: Use wrangler secret put MCP_IDENTITY_PRIVATE_KEY
|
|
750
|
-
|
|
751
|
-
# ALLOWED_ORIGINS for CORS (update for production)
|
|
752
|
-
ALLOWED_ORIGINS = "https://claude.ai,https://app.anthropic.com"
|
|
753
|
-
|
|
754
|
-
# DO routing strategy: "session" for dev, "shard" for production high-load
|
|
755
|
-
DO_ROUTING_STRATEGY = "session"
|
|
756
|
-
DO_SHARD_COUNT = "10" # Number of shards if using shard strategy
|
|
757
|
-
|
|
758
|
-
`;
|
|
759
|
-
// Remove any secret declarations from [vars] (they should not be here)
|
|
760
|
-
// Secrets go in .dev.vars for local dev, wrangler secret put for production
|
|
761
|
-
wranglerTomlContent = wranglerTomlContent.replace(/^\s*MCP_IDENTITY_PRIVATE_KEY\s*=.*$/gm, `# MCP_IDENTITY_PRIVATE_KEY - SECRET (not declared here, see .dev.vars or wrangler secret put)`);
|
|
762
|
-
wranglerTomlContent = wranglerTomlContent.replace(/^\s*AGENTSHIELD_API_KEY\s*=.*$/gm, `# AGENTSHIELD_API_KEY - SECRET (not declared here, see .dev.vars or wrangler secret put)`);
|
|
763
|
-
wranglerTomlContent = wranglerTomlContent.replace(/^\s*ADMIN_API_KEY\s*=.*$/gm, `# ADMIN_API_KEY - SECRET (not declared here, see .dev.vars or wrangler secret put)`);
|
|
764
|
-
// Update public key if it exists (safe to keep in [vars])
|
|
765
|
-
if (/MCP_IDENTITY_PUBLIC_KEY\s*=/.test(wranglerTomlContent)) {
|
|
766
|
-
wranglerTomlContent = wranglerTomlContent.replace(/MCP_IDENTITY_PUBLIC_KEY\s*=\s*"[^"]*"/, `MCP_IDENTITY_PUBLIC_KEY = "${identity.publicKey}"`);
|
|
767
|
-
}
|
|
768
|
-
// Update AGENTSHIELD_PROJECT_ID if it exists and projectId is provided
|
|
769
|
-
// This is safe to keep a value since it's not sensitive
|
|
770
|
-
if (projectId &&
|
|
771
|
-
/AGENTSHIELD_PROJECT_ID\s*=/.test(wranglerTomlContent)) {
|
|
772
|
-
wranglerTomlContent = wranglerTomlContent.replace(/AGENTSHIELD_PROJECT_ID\s*=\s*"[^"]*"/, `AGENTSHIELD_PROJECT_ID = "${projectId}"`);
|
|
773
|
-
}
|
|
774
|
-
// Check if non-secret variables already exist in wrangler.toml
|
|
775
|
-
const hasIdentityDid = /MCP_IDENTITY_AGENT_DID\s*=/.test(wranglerTomlContent);
|
|
776
|
-
const hasIdentityPublicKey = /MCP_IDENTITY_PUBLIC_KEY\s*=/.test(wranglerTomlContent);
|
|
777
|
-
// Only insert identity vars if they don't already exist
|
|
778
|
-
const needsInsertion = !hasIdentityDid || !hasIdentityPublicKey;
|
|
779
|
-
if (needsInsertion) {
|
|
780
|
-
wranglerTomlContent =
|
|
781
|
-
wranglerTomlContent.slice(0, insertPosition) +
|
|
782
|
-
identityVars +
|
|
783
|
-
wranglerTomlContent.slice(insertPosition);
|
|
784
|
-
}
|
|
785
|
-
// Write updated wrangler.toml (without secrets)
|
|
786
|
-
fs.writeFileSync(wranglerPath, wranglerTomlContent);
|
|
787
|
-
// Create .dev.vars file for local development (git-ignored)
|
|
788
|
-
// Only contains SECRETS (not public keys or project IDs)
|
|
789
|
-
const devVarsPath = path.join(projectPath, ".dev.vars");
|
|
790
|
-
const devVarsContent = `# Local development secrets (DO NOT COMMIT)
|
|
791
|
-
# This file is git-ignored and contains sensitive data
|
|
792
|
-
#
|
|
793
|
-
# HOW IT WORKS:
|
|
794
|
-
# 1. Secrets are NOT declared in wrangler.toml [vars] (avoids conflicts)
|
|
795
|
-
# 2. This file (.dev.vars) provides secrets for local development
|
|
796
|
-
# 3. Production uses: wrangler secret put VARIABLE_NAME
|
|
797
|
-
#
|
|
798
|
-
# Non-secrets (MCP_IDENTITY_PUBLIC_KEY, AGENTSHIELD_PROJECT_ID) are in wrangler.toml
|
|
799
|
-
|
|
800
|
-
# Private identity key (generated by create-mcpi-app)
|
|
801
|
-
MCP_IDENTITY_PRIVATE_KEY="${identity.privateKey}"
|
|
802
|
-
|
|
803
|
-
# AgentShield API key (get from https://kya.vouched.id/dashboard)
|
|
804
|
-
AGENTSHIELD_API_KEY="${apikey || ""}"${apikey ? " # Provided via --apikey flag" : ""}
|
|
805
|
-
|
|
806
|
-
# Admin API key for protected endpoints (set to same value as AGENTSHIELD_API_KEY)
|
|
807
|
-
ADMIN_API_KEY="${apikey || ""}"${apikey ? " # Set to same value as AGENTSHIELD_API_KEY" : ""}
|
|
260
|
+
# MCP_SERVER_URL = "https://${projectName}.YOUR-SUBDOMAIN.workers.dev"
|
|
808
261
|
`;
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
#
|
|
815
|
-
# NOTE: Only secrets go here. Non-secrets (MCP_IDENTITY_PUBLIC_KEY, AGENTSHIELD_PROJECT_ID)
|
|
816
|
-
# are in wrangler.toml [vars] and can be committed safely.
|
|
817
|
-
|
|
818
|
-
# Private identity key (generate with: npx @kya-os/create-mcpi-app regenerate-identity)
|
|
819
|
-
MCP_IDENTITY_PRIVATE_KEY="your-private-key-here"
|
|
262
|
+
await fs.writeFile(path.join(targetDir, "wrangler.toml"), wranglerToml);
|
|
263
|
+
// 6. Create src/index.ts (Entry Point)
|
|
264
|
+
const indexTs = `import { createMCPIApp } from "@kya-os/mcp-i-cloudflare";
|
|
265
|
+
import { ${toPascalCase(projectName)}MCP } from "./agent";
|
|
266
|
+
import { getRuntimeConfig } from "./mcpi-runtime-config";
|
|
820
267
|
|
|
821
|
-
|
|
822
|
-
|
|
268
|
+
export default createMCPIApp({
|
|
269
|
+
AgentClass: ${toPascalCase(projectName)}MCP,
|
|
270
|
+
getRuntimeConfig,
|
|
271
|
+
});
|
|
823
272
|
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
`;
|
|
827
|
-
fs.writeFileSync(devVarsExamplePath, devVarsExampleContent);
|
|
828
|
-
console.log(chalk.green("ā
Generated persistent identity"));
|
|
829
|
-
console.log(chalk.dim(` DID: ${identity.did}`));
|
|
830
|
-
console.log(chalk.green("ā
Created secure configuration:"));
|
|
831
|
-
console.log(chalk.dim(" ⢠Public DID in wrangler.toml (safe to commit)"));
|
|
832
|
-
console.log(chalk.dim(" ⢠Private keys in .dev.vars (git-ignored)"));
|
|
833
|
-
console.log(chalk.dim(" ⢠Example template in .dev.vars.example"));
|
|
834
|
-
console.log();
|
|
835
|
-
console.log(chalk.yellow("š Production Security:"));
|
|
836
|
-
console.log(chalk.dim(" Secrets are NOT in wrangler.toml (cleaner approach)"));
|
|
837
|
-
console.log(chalk.dim(" For production, set secrets using wrangler:"));
|
|
838
|
-
console.log(chalk.cyan(" $ wrangler secret put MCP_IDENTITY_PRIVATE_KEY"));
|
|
839
|
-
console.log(chalk.cyan(" $ wrangler secret put AGENTSHIELD_API_KEY"));
|
|
840
|
-
console.log(chalk.cyan(" $ wrangler secret put ADMIN_API_KEY"));
|
|
841
|
-
console.log();
|
|
842
|
-
console.log(chalk.dim(" Tip: Copy values from .dev.vars when prompted"));
|
|
843
|
-
console.log();
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
catch (error) {
|
|
847
|
-
console.log(chalk.yellow("ā ļø Failed to generate identity:"), error.message);
|
|
848
|
-
console.log(chalk.dim(" You can generate one later with:"));
|
|
849
|
-
console.log(chalk.cyan(" $ npx @kya-os/create-mcpi-app regenerate-identity"));
|
|
850
|
-
console.log();
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
// Create tsconfig.json
|
|
854
|
-
fs.ensureDirSync(projectPath); // Ensure directory exists before writing
|
|
855
|
-
const tsconfigContent = {
|
|
856
|
-
compilerOptions: {
|
|
857
|
-
target: "ES2022",
|
|
858
|
-
module: "ES2022",
|
|
859
|
-
lib: ["ES2022"],
|
|
860
|
-
types: ["@cloudflare/workers-types"],
|
|
861
|
-
moduleResolution: "bundler",
|
|
862
|
-
resolveJsonModule: true,
|
|
863
|
-
allowSyntheticDefaultImports: true,
|
|
864
|
-
esModuleInterop: true,
|
|
865
|
-
strict: true,
|
|
866
|
-
skipLibCheck: true,
|
|
867
|
-
forceConsistentCasingInFileNames: true,
|
|
868
|
-
},
|
|
869
|
-
include: ["src/**/*"],
|
|
870
|
-
};
|
|
871
|
-
fs.writeJsonSync(path.join(projectPath, "tsconfig.json"), tsconfigContent, {
|
|
872
|
-
spaces: 2,
|
|
873
|
-
});
|
|
874
|
-
// Create .gitignore
|
|
875
|
-
const gitignoreContent = `node_modules/
|
|
876
|
-
dist/
|
|
877
|
-
.wrangler/
|
|
878
|
-
.dev.vars
|
|
879
|
-
.env
|
|
880
|
-
.env.local
|
|
881
|
-
*.log
|
|
273
|
+
// Export Durable Object class for Cloudflare Workers binding
|
|
274
|
+
export { ${toPascalCase(projectName)}MCP };
|
|
882
275
|
`;
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
loglevel=error
|
|
890
|
-
`;
|
|
891
|
-
fs.writeFileSync(path.join(projectPath, ".npmrc"), npmrcContent);
|
|
892
|
-
// Create README.md
|
|
893
|
-
const readmeContent = `# ${projectName}
|
|
894
|
-
|
|
895
|
-
MCP server running on Cloudflare Workers with MCP-I identity features, cryptographic proofs, and full SSE/HTTP streaming support.
|
|
896
|
-
|
|
897
|
-
## Features
|
|
898
|
-
|
|
899
|
-
- ā
**MCP Protocol Support**: SSE and HTTP streaming transports
|
|
900
|
-
- ā
**Cryptographic Identity**: DID-based agent identity with Ed25519 signatures
|
|
901
|
-
- ā
**Proof Generation**: Every tool call generates a cryptographic proof
|
|
902
|
-
- ā
**Audit Logging**: Track all operations with proof IDs and signatures
|
|
903
|
-
- ā
**Nonce Protection**: Replay attack prevention via KV-backed nonce cache
|
|
904
|
-
- ā
**Proof Archiving**: Optional KV storage for proof history
|
|
905
|
-
|
|
906
|
-
## Quick Start
|
|
907
|
-
|
|
908
|
-
### 1. Install Dependencies
|
|
909
|
-
|
|
910
|
-
\`\`\`bash
|
|
911
|
-
${packageManager} install
|
|
912
|
-
\`\`\`
|
|
913
|
-
|
|
914
|
-
### 2. Create KV Namespaces
|
|
915
|
-
|
|
916
|
-
#### Create All KV Namespaces (Recommended)
|
|
917
|
-
|
|
918
|
-
\`\`\`bash
|
|
919
|
-
${packageManager === "npm" ? "npm run" : packageManager} kv:create
|
|
920
|
-
\`\`\`
|
|
921
|
-
|
|
922
|
-
This creates all 5 KV namespaces at once:
|
|
923
|
-
- \`NONCE_CACHE\` - Replay attack prevention (Required)
|
|
924
|
-
- \`PROOF_ARCHIVE\` - Cryptographic proof storage (Recommended)
|
|
925
|
-
- \`IDENTITY_STORAGE\` - Agent identity persistence (Recommended)
|
|
926
|
-
- \`DELEGATION_STORAGE\` - OAuth delegation storage (Required for delegation)
|
|
927
|
-
- \`TOOL_PROTECTION_KV\` - Dashboard-controlled permissions (Optional)
|
|
928
|
-
|
|
929
|
-
Copy the namespace IDs from the output and update each one in \`wrangler.toml\`:
|
|
930
|
-
|
|
931
|
-
\`\`\`toml
|
|
932
|
-
[[kv_namespaces]]
|
|
933
|
-
binding = "NONCE_CACHE"
|
|
934
|
-
id = "your_nonce_kv_id_here" # ā Update this
|
|
935
|
-
|
|
936
|
-
[[kv_namespaces]]
|
|
937
|
-
binding = "PROOF_ARCHIVE"
|
|
938
|
-
id = "your_proof_kv_id_here" # ā Update this
|
|
939
|
-
|
|
940
|
-
[[kv_namespaces]]
|
|
941
|
-
binding = "IDENTITY_STORAGE"
|
|
942
|
-
id = "your_identity_kv_id_here" # ā Update this
|
|
943
|
-
|
|
944
|
-
[[kv_namespaces]]
|
|
945
|
-
binding = "DELEGATION_STORAGE"
|
|
946
|
-
id = "your_delegation_kv_id_here" # ā Update this
|
|
947
|
-
|
|
948
|
-
[[kv_namespaces]]
|
|
949
|
-
binding = "TOOL_PROTECTION_KV"
|
|
950
|
-
id = "your_tool_protection_kv_id_here" # ā Update this
|
|
951
|
-
\`\`\`
|
|
952
|
-
|
|
953
|
-
**Note:** You can also create namespaces individually:
|
|
954
|
-
- \`${packageManager === "npm" ? "npm run" : packageManager} kv:create-nonce\` - Create nonce cache only
|
|
955
|
-
- \`${packageManager === "npm" ? "npm run" : packageManager} kv:create-proof\` - Create proof archive only
|
|
956
|
-
- \`${packageManager === "npm" ? "npm run" : packageManager} kv:create-identity\` - Create identity storage only
|
|
957
|
-
- \`${packageManager === "npm" ? "npm run" : packageManager} kv:create-delegation\` - Create delegation storage only
|
|
958
|
-
- \`${packageManager === "npm" ? "npm run" : packageManager} kv:create-tool-protection\` - Create tool protection cache only
|
|
959
|
-
|
|
960
|
-
### 3. Test Locally
|
|
961
|
-
|
|
962
|
-
\`\`\`bash
|
|
963
|
-
${packageManager === "npm" ? "npm run" : packageManager} dev
|
|
964
|
-
\`\`\`
|
|
965
|
-
|
|
966
|
-
### 4. Deploy
|
|
967
|
-
|
|
968
|
-
#### Production Deployment
|
|
969
|
-
|
|
970
|
-
Secrets are **not** declared in \`wrangler.toml\` to avoid conflicts. Set them using:
|
|
971
|
-
|
|
972
|
-
\`\`\`bash
|
|
973
|
-
wrangler secret put MCP_IDENTITY_PRIVATE_KEY
|
|
974
|
-
wrangler secret put AGENTSHIELD_API_KEY
|
|
975
|
-
wrangler secret put ADMIN_API_KEY
|
|
976
|
-
\`\`\`
|
|
977
|
-
|
|
978
|
-
**Tip:** Copy values from your \`.dev.vars\` file when prompted.
|
|
979
|
-
|
|
980
|
-
**Note:** \`MCP_IDENTITY_PUBLIC_KEY\` and \`AGENTSHIELD_PROJECT_ID\` are not secrets and are already in \`wrangler.toml\` with values.
|
|
981
|
-
|
|
982
|
-
Now deploy:
|
|
276
|
+
await fs.writeFile(path.join(targetDir, "src/index.ts"), indexTs);
|
|
277
|
+
// 7. Create src/agent.ts (Agent Class)
|
|
278
|
+
const agentTs = `import { MCPICloudflareAgent, type CloudflareEnv } from "@kya-os/mcp-i-cloudflare";
|
|
279
|
+
import { getRuntimeConfig } from "./mcpi-runtime-config";
|
|
280
|
+
import { getTools } from "./mcpi-runtime-config";
|
|
281
|
+
import type { CloudflareRuntimeConfig } from "@kya-os/mcp-i-cloudflare";
|
|
983
282
|
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
283
|
+
/**
|
|
284
|
+
* MCP-I Agent Implementation
|
|
285
|
+
*
|
|
286
|
+
* This class extends MCPICloudflareAgent and provides the agent-specific
|
|
287
|
+
* configuration and tool registration. The Durable Object class (${toPascalCase(projectName)}MCP)
|
|
288
|
+
* is exported separately for Cloudflare Workers bindings.
|
|
289
|
+
*/
|
|
290
|
+
export class ${toPascalCase(projectName)}MCP extends MCPICloudflareAgent {
|
|
291
|
+
/**
|
|
292
|
+
* Get agent name
|
|
293
|
+
*/
|
|
294
|
+
protected getAgentName(): string {
|
|
295
|
+
return "${projectName}";
|
|
296
|
+
}
|
|
987
297
|
|
|
988
|
-
|
|
298
|
+
/**
|
|
299
|
+
* Get agent version
|
|
300
|
+
*/
|
|
301
|
+
protected getAgentVersion(): string {
|
|
302
|
+
return "1.0.0";
|
|
303
|
+
}
|
|
989
304
|
|
|
990
|
-
|
|
305
|
+
/**
|
|
306
|
+
* Get runtime configuration
|
|
307
|
+
* This is called during agent initialization and has access to the environment
|
|
308
|
+
*/
|
|
309
|
+
protected getRuntimeConfigInternal(env: CloudflareEnv): CloudflareRuntimeConfig {
|
|
310
|
+
return getRuntimeConfig(env);
|
|
311
|
+
}
|
|
991
312
|
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
313
|
+
/**
|
|
314
|
+
* Register tools with the MCP server
|
|
315
|
+
* Tools are defined in mcpi-runtime-config.ts
|
|
316
|
+
*/
|
|
317
|
+
protected async registerTools(): Promise<void> {
|
|
318
|
+
// Get tools from the tools registry
|
|
319
|
+
const tools = getTools();
|
|
320
|
+
|
|
321
|
+
// Register each tool with proof generation
|
|
322
|
+
for (const toolDef of tools) {
|
|
323
|
+
this.registerToolWithProof(
|
|
324
|
+
toolDef.name,
|
|
325
|
+
toolDef.description,
|
|
326
|
+
toolDef.inputSchema, // JSON schema format (MCP protocol standard)
|
|
327
|
+
toolDef.handler
|
|
328
|
+
);
|
|
998
329
|
}
|
|
999
330
|
}
|
|
1000
331
|
}
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
Restart Claude Desktop and test: "Use the greet tool to say hello to Alice"
|
|
1006
|
-
|
|
1007
|
-
## Adding Tools
|
|
1008
|
-
|
|
1009
|
-
Create tools in \`src/tools/\`:
|
|
1010
|
-
|
|
1011
|
-
\`\`\`typescript
|
|
1012
|
-
import { z } from "zod";
|
|
332
|
+
`;
|
|
333
|
+
await fs.writeFile(path.join(targetDir, "src/agent.ts"), agentTs);
|
|
334
|
+
// 8. Create src/tools/greet.ts
|
|
335
|
+
const greetToolTs = `import type { ToolDefinition } from "@kya-os/mcp-i-cloudflare";
|
|
1013
336
|
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
337
|
+
/**
|
|
338
|
+
* Greet tool definition
|
|
339
|
+
*
|
|
340
|
+
* This tool demonstrates a simple MCP tool implementation.
|
|
341
|
+
* Tools are registered with the MCP server and can be called by MCP clients.
|
|
342
|
+
*/
|
|
343
|
+
export const greetTool: ToolDefinition = {
|
|
344
|
+
name: "greet",
|
|
345
|
+
description: "Greet the user",
|
|
346
|
+
inputSchema: {
|
|
347
|
+
type: "object",
|
|
348
|
+
properties: {
|
|
349
|
+
name: { type: "string", description: "Name of the person to greet" },
|
|
350
|
+
},
|
|
351
|
+
required: ["name"],
|
|
352
|
+
},
|
|
353
|
+
handler: async (args: { name: string }) => {
|
|
354
|
+
return {
|
|
355
|
+
content: [
|
|
356
|
+
{
|
|
357
|
+
type: "text",
|
|
358
|
+
text: \`Hello, \${args.name}! Welcome to ${projectName}.\`,
|
|
359
|
+
},
|
|
360
|
+
],
|
|
361
|
+
};
|
|
362
|
+
},
|
|
1023
363
|
};
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
myTool.name,
|
|
1031
|
-
myTool.description,
|
|
1032
|
-
myTool.inputSchema.shape,
|
|
1033
|
-
myTool.handler
|
|
1034
|
-
);
|
|
1035
|
-
\`\`\`
|
|
1036
|
-
|
|
1037
|
-
## Endpoints
|
|
1038
|
-
|
|
1039
|
-
- \`/health\` - Health check
|
|
1040
|
-
- \`/sse\` - SSE transport for MCP
|
|
1041
|
-
- \`/mcp\` - Streamable HTTP transport for MCP
|
|
1042
|
-
- \`/oauth/callback\` - OAuth callback for delegation flows
|
|
1043
|
-
- \`/admin/clear-cache\` - Clear tool protection cache (requires API key)
|
|
1044
|
-
|
|
1045
|
-
## Viewing Cryptographic Proofs
|
|
1046
|
-
|
|
1047
|
-
Every tool call generates a cryptographic proof that's logged to the console:
|
|
1048
|
-
|
|
1049
|
-
\`\`\`bash
|
|
1050
|
-
${packageManager === "npm" ? "npm run" : packageManager} dev
|
|
1051
|
-
\`\`\`
|
|
1052
|
-
|
|
1053
|
-
When you call a tool, you'll see logs like:
|
|
364
|
+
`;
|
|
365
|
+
await fs.writeFile(path.join(targetDir, "src/tools/greet.ts"), greetToolTs);
|
|
366
|
+
// 9. Create src/mcpi-runtime-config.ts
|
|
367
|
+
const runtimeConfigTs = `import { defineConfig, type CloudflareRuntimeConfig } from "@kya-os/mcp-i-cloudflare";
|
|
368
|
+
import type { CloudflareEnv } from "@kya-os/mcp-i-cloudflare";
|
|
369
|
+
import { greetTool } from "./tools/greet";
|
|
1054
370
|
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
371
|
+
/**
|
|
372
|
+
* Get runtime configuration for MCP-I Cloudflare Worker
|
|
373
|
+
*
|
|
374
|
+
* This function is called by the framework to get the runtime configuration.
|
|
375
|
+
*/
|
|
376
|
+
export function getRuntimeConfig(env: CloudflareEnv): CloudflareRuntimeConfig {
|
|
377
|
+
// Determine environment with proper type casting
|
|
378
|
+
const environment = (env.MCPI_ENV || env.ENVIRONMENT || "development") as "development" | "production";
|
|
379
|
+
|
|
380
|
+
return defineConfig({
|
|
381
|
+
environment,
|
|
382
|
+
// Add other configuration options as needed
|
|
383
|
+
});
|
|
1062
384
|
}
|
|
1063
|
-
\`\`\`
|
|
1064
|
-
|
|
1065
|
-
### Proof Archives (Optional)
|
|
1066
|
-
|
|
1067
|
-
If you configured the \`PROOF_ARCHIVE\` KV namespace, proofs are also stored for querying:
|
|
1068
|
-
|
|
1069
|
-
\`\`\`bash
|
|
1070
|
-
# List all proofs
|
|
1071
|
-
wrangler kv:key list --namespace-id=your_proof_kv_id
|
|
1072
|
-
|
|
1073
|
-
# View a specific proof
|
|
1074
|
-
wrangler kv:key get "proof_1234567890_abcd" --namespace-id=your_proof_kv_id
|
|
1075
|
-
\`\`\`
|
|
1076
|
-
|
|
1077
|
-
## Identity Management
|
|
1078
|
-
|
|
1079
|
-
Your agent's cryptographic identity is stored in Durable Objects state. To view your agent's DID:
|
|
1080
|
-
|
|
1081
|
-
1. Check the logs during \`init()\` - it prints the DID
|
|
1082
|
-
2. Or query the runtime: \`await mcpiRuntime.getIdentity()\`
|
|
1083
|
-
|
|
1084
|
-
The identity includes:
|
|
1085
|
-
- \`did\`: Decentralized identifier (e.g., \`did:web:your-worker.workers.dev:agents:key-xyz\`)
|
|
1086
|
-
- \`publicKey\`: Ed25519 public key for signature verification
|
|
1087
|
-
- \`privateKey\`: Ed25519 private key (secured in Durable Object state)
|
|
1088
|
-
|
|
1089
|
-
## AgentShield Integration
|
|
1090
|
-
|
|
1091
|
-
This project is configured to send cryptographic proofs to AgentShield for audit trails and compliance monitoring.
|
|
1092
|
-
|
|
1093
|
-
### Setup
|
|
1094
|
-
|
|
1095
|
-
1. **Get your AgentShield API key**:
|
|
1096
|
-
- Sign up at https://kya.vouched.id
|
|
1097
|
-
- Create a project
|
|
1098
|
-
- Copy your API key from the dashboard
|
|
1099
|
-
|
|
1100
|
-
2. **Update \`wrangler.toml\`**:
|
|
1101
|
-
\`\`\`toml
|
|
1102
|
-
[vars]
|
|
1103
|
-
AGENTSHIELD_API_URL = "https://kya.vouched.id"
|
|
1104
|
-
AGENTSHIELD_API_KEY = "sk_your_actual_key_here" # ā Replace this
|
|
1105
|
-
MCPI_ENV = "development"
|
|
1106
|
-
\`\`\`
|
|
1107
|
-
|
|
1108
|
-
3. **Test proof submission**:
|
|
1109
|
-
\`\`\`bash
|
|
1110
|
-
${packageManager === "npm" ? "npm run" : packageManager} dev
|
|
1111
|
-
\`\`\`
|
|
1112
|
-
|
|
1113
|
-
Call a tool and check the logs:
|
|
1114
|
-
\`\`\`
|
|
1115
|
-
[AgentShield] Submitting proof: { did: 'did:web:...', sessionId: '...', jwsFormat: 'valid (3 parts)' }
|
|
1116
|
-
[AgentShield] ā
Proofs accepted: 1
|
|
1117
|
-
\`\`\`
|
|
1118
|
-
|
|
1119
|
-
4. **View proofs in dashboard**:
|
|
1120
|
-
- Go to https://kya.vouched.id/dashboard
|
|
1121
|
-
- Select your project
|
|
1122
|
-
- Click "Interactions" tab
|
|
1123
|
-
- See your proofs in real-time
|
|
1124
385
|
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
- Toggle "Require Delegation" for any tool
|
|
1164
|
-
- Changes apply in real-time (5-minute cache)
|
|
1165
|
-
|
|
1166
|
-
**Benefits:**
|
|
1167
|
-
- Update tool permissions without redeploying
|
|
1168
|
-
- Test delegation flows instantly
|
|
1169
|
-
- Different requirements per environment (dev vs prod)
|
|
1170
|
-
- Automatic tool discovery from proof submissions
|
|
1171
|
-
|
|
1172
|
-
**Note:** The first time a tool is called, it auto-discovers in the dashboard. The \`requiresDelegation\` toggle will appear after the first proof is submitted.
|
|
386
|
+
/**
|
|
387
|
+
* Get all tools for this agent
|
|
388
|
+
*
|
|
389
|
+
* Tools are registered separately from the runtime config.
|
|
390
|
+
* This function is called by the agent to get the list of tools.
|
|
391
|
+
*/
|
|
392
|
+
export function getTools() {
|
|
393
|
+
return [
|
|
394
|
+
greetTool,
|
|
395
|
+
// Add more tools here
|
|
396
|
+
];
|
|
397
|
+
}
|
|
398
|
+
`;
|
|
399
|
+
await fs.writeFile(path.join(targetDir, "src/mcpi-runtime-config.ts"), runtimeConfigTs);
|
|
400
|
+
// 10. Create scripts/setup.js (KV Namespace Creation & Key Regeneration Script)
|
|
401
|
+
const setupJs = `#!/usr/bin/env node
|
|
402
|
+
const { execSync } = require('child_process');
|
|
403
|
+
const fs = require('fs');
|
|
404
|
+
const path = require('path');
|
|
405
|
+
const crypto = require('crypto');
|
|
406
|
+
|
|
407
|
+
const projectName = '${projectName}';
|
|
408
|
+
const projectNameUpper = '${projectNameUpper}';
|
|
409
|
+
|
|
410
|
+
console.log('š Setting up MCP-I Cloudflare Worker...');
|
|
411
|
+
console.log('');
|
|
412
|
+
|
|
413
|
+
// Check if user is logged in to Cloudflare
|
|
414
|
+
console.log('š Checking Cloudflare authentication...');
|
|
415
|
+
try {
|
|
416
|
+
execSync('wrangler whoami', { encoding: 'utf8', stdio: 'pipe' });
|
|
417
|
+
console.log('ā
Logged in to Cloudflare\\n');
|
|
418
|
+
} catch (error) {
|
|
419
|
+
console.error('ā Not logged in to Cloudflare!\\n');
|
|
420
|
+
console.error('Please run: wrangler login\\n');
|
|
421
|
+
console.error('Then run this setup script again: npm run setup\\n');
|
|
422
|
+
process.exit(1);
|
|
423
|
+
}
|
|
1173
424
|
|
|
1174
|
-
|
|
425
|
+
// Function to execute command and capture output
|
|
426
|
+
function exec(command, silent = false) {
|
|
427
|
+
try {
|
|
428
|
+
const output = execSync(command, { encoding: 'utf8', stdio: silent ? 'pipe' : 'inherit' });
|
|
429
|
+
return output?.trim();
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (!silent) {
|
|
432
|
+
console.error(\`ā Command failed: \${command}\`);
|
|
433
|
+
console.error(error.message);
|
|
434
|
+
if (error.stderr) {
|
|
435
|
+
console.error('Error output:', error.stderr.toString());
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
throw error; // Re-throw to handle in caller
|
|
439
|
+
}
|
|
440
|
+
}
|
|
1175
441
|
|
|
1176
|
-
|
|
442
|
+
// Function to extract namespace ID from wrangler output
|
|
443
|
+
function extractNamespaceId(output) {
|
|
444
|
+
// Match patterns like: id = "abc123" or { id: "abc123" }
|
|
445
|
+
const match = output.match(/id\\s*[:=]\\s*"([^"]+)"/);
|
|
446
|
+
return match ? match[1] : null;
|
|
447
|
+
}
|
|
1177
448
|
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
449
|
+
// Function to update wrangler.toml with namespace ID
|
|
450
|
+
function updateWranglerToml(binding, namespaceId) {
|
|
451
|
+
const wranglerPath = path.join(__dirname, '..', 'wrangler.toml');
|
|
452
|
+
let content = fs.readFileSync(wranglerPath, 'utf8');
|
|
453
|
+
|
|
454
|
+
// Find the binding section and update the ID
|
|
455
|
+
const bindingPattern = new RegExp(\`binding\\\\s*=\\\\s*"\${binding}"[^\\\\[]*id\\\\s*=\\\\s*"[^"]*"\`, 's');
|
|
456
|
+
content = content.replace(bindingPattern, (match) => {
|
|
457
|
+
return match.replace(/id\\s*=\\s*"[^"]*"/, \`id = "\${namespaceId}"\`);
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
fs.writeFileSync(wranglerPath, content);
|
|
461
|
+
console.log(\`ā
Updated wrangler.toml with \${binding} namespace ID: \${namespaceId}\`);
|
|
1182
462
|
}
|
|
1183
|
-
\`\`\`
|
|
1184
463
|
|
|
1185
|
-
|
|
464
|
+
// Create KV namespaces
|
|
465
|
+
const namespaces = [
|
|
466
|
+
{ binding: \`\${projectNameUpper}_NONCE_CACHE\`, name: 'NONCE_CACHE', description: 'Nonce cache for replay attack prevention' },
|
|
467
|
+
{ binding: \`\${projectNameUpper}_PROOF_ARCHIVE\`, name: 'PROOF_ARCHIVE', description: 'Proof archive for auditability' },
|
|
468
|
+
{ binding: \`\${projectNameUpper}_IDENTITY_STORAGE\`, name: 'IDENTITY_STORAGE', description: 'Identity storage for persistent agent identity' },
|
|
469
|
+
{ binding: \`\${projectNameUpper}_DELEGATION_STORAGE\`, name: 'DELEGATION_STORAGE', description: 'Delegation storage for OAuth flows' },
|
|
470
|
+
{ binding: \`\${projectNameUpper}_TOOL_PROTECTION_KV\`, name: 'TOOL_PROTECTION_KV', description: 'Tool protection configuration cache' },
|
|
471
|
+
];
|
|
472
|
+
|
|
473
|
+
console.log('š¦ Creating KV namespaces...');
|
|
474
|
+
console.log('');
|
|
475
|
+
|
|
476
|
+
let successCount = 0;
|
|
477
|
+
let failureCount = 0;
|
|
478
|
+
|
|
479
|
+
for (const ns of namespaces) {
|
|
480
|
+
console.log(\`\\nš¦ Creating \${ns.name}...\`);
|
|
481
|
+
console.log(\` Description: \${ns.description}\`);
|
|
482
|
+
|
|
483
|
+
try {
|
|
484
|
+
// Try to create the namespace
|
|
485
|
+
const output = exec(\`wrangler kv:namespace create \${ns.binding}\`, true);
|
|
486
|
+
|
|
487
|
+
if (output) {
|
|
488
|
+
console.log(\` Raw output: \${output.substring(0, 200)}\`);
|
|
489
|
+
|
|
490
|
+
const namespaceId = extractNamespaceId(output);
|
|
491
|
+
if (namespaceId) {
|
|
492
|
+
updateWranglerToml(ns.binding, namespaceId);
|
|
493
|
+
console.log(\` ā
Created successfully!\`);
|
|
494
|
+
successCount++;
|
|
495
|
+
} else {
|
|
496
|
+
console.log(\` ā ļø Could not extract namespace ID from output.\`);
|
|
497
|
+
console.log(\` Full output: \${output}\`);
|
|
498
|
+
console.log(\` You may need to update wrangler.toml manually.\`);
|
|
499
|
+
failureCount++;
|
|
500
|
+
}
|
|
501
|
+
} else {
|
|
502
|
+
console.log(\` ā ļø No output from wrangler command.\`);
|
|
503
|
+
failureCount++;
|
|
504
|
+
}
|
|
505
|
+
} catch (error) {
|
|
506
|
+
// Namespace might already exist
|
|
507
|
+
console.log(\` ā¹ļø Namespace may already exist. Checking...\`);
|
|
508
|
+
try {
|
|
509
|
+
const listOutput = exec(\`wrangler kv:namespace list\`, true);
|
|
510
|
+
if (listOutput && listOutput.includes(ns.binding)) {
|
|
511
|
+
console.log(\` ā Namespace \${ns.binding} already exists\`);
|
|
512
|
+
|
|
513
|
+
// Try to extract ID from list output
|
|
514
|
+
const listJson = JSON.parse(listOutput);
|
|
515
|
+
const existing = listJson.find(item => item.title.includes(ns.binding));
|
|
516
|
+
if (existing && existing.id) {
|
|
517
|
+
updateWranglerToml(ns.binding, existing.id);
|
|
518
|
+
console.log(\` ā
Updated wrangler.toml with existing ID: \${existing.id}\`);
|
|
519
|
+
successCount++;
|
|
520
|
+
} else {
|
|
521
|
+
console.log(\` ā ļø Found namespace but could not extract ID. Update wrangler.toml manually.\`);
|
|
522
|
+
failureCount++;
|
|
523
|
+
}
|
|
524
|
+
} else {
|
|
525
|
+
console.log(\` ā Could not create or find namespace \${ns.binding}.\`);
|
|
526
|
+
console.log(\` Error: \${error.message}\`);
|
|
527
|
+
console.log(\` You may need to create it manually with: wrangler kv:namespace create \${ns.binding}\`);
|
|
528
|
+
failureCount++;
|
|
529
|
+
}
|
|
530
|
+
} catch (listError) {
|
|
531
|
+
console.log(\` ā Failed to list namespaces: \${listError.message}\`);
|
|
532
|
+
failureCount++;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
1186
536
|
|
|
1187
|
-
|
|
537
|
+
console.log('');
|
|
538
|
+
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā');
|
|
539
|
+
console.log('š Setup Summary:');
|
|
540
|
+
console.log(\` ā
Success: \${successCount}/\${namespaces.length} namespaces\`);
|
|
541
|
+
console.log(\` ā Failed: \${failureCount}/\${namespaces.length} namespaces\`);
|
|
542
|
+
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\\n');
|
|
543
|
+
|
|
544
|
+
if (failureCount > 0) {
|
|
545
|
+
console.log('ā ļø Some namespaces failed to create.\\n');
|
|
546
|
+
console.log('Manual steps required:');
|
|
547
|
+
console.log('1. Check wrangler.toml for any "TODO_REPLACE_WITH_ID" entries');
|
|
548
|
+
console.log('2. Create missing namespaces manually with:');
|
|
549
|
+
console.log(' wrangler kv:namespace create NAMESPACE_BINDING\\n');
|
|
550
|
+
console.log('3. Copy the ID from the output to wrangler.toml\\n');
|
|
551
|
+
} else {
|
|
552
|
+
console.log('⨠Setup complete!\\n');
|
|
553
|
+
}
|
|
1188
554
|
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
555
|
+
console.log('š Next steps:');
|
|
556
|
+
console.log('1. Review wrangler.toml to ensure all namespace IDs are populated');
|
|
557
|
+
console.log('2. Review .dev.vars for secrets configuration');
|
|
558
|
+
console.log('3. Run "npm run dev" to start the development server');
|
|
559
|
+
console.log('4. Run "npm run deploy" to deploy to Cloudflare Workers\\n');
|
|
560
|
+
|
|
561
|
+
console.log('š For production deployment:');
|
|
562
|
+
console.log(' wrangler secret put MCP_IDENTITY_PRIVATE_KEY');
|
|
563
|
+
if (failureCount === 0) {
|
|
564
|
+
console.log(' wrangler secret put AGENTSHIELD_API_KEY');
|
|
565
|
+
console.log(' # ADMIN_API_KEY is optional - falls back to AGENTSHIELD_API_KEY if not set');
|
|
566
|
+
}
|
|
567
|
+
`;
|
|
568
|
+
await fs.writeFile(path.join(targetDir, "scripts/setup.js"), setupJs);
|
|
569
|
+
await fs.chmod(path.join(targetDir, "scripts/setup.js"), "755");
|
|
570
|
+
// 11. Create tsconfig.json
|
|
571
|
+
const tsConfig = {
|
|
572
|
+
compilerOptions: {
|
|
573
|
+
target: "esnext",
|
|
574
|
+
module: "esnext",
|
|
575
|
+
moduleResolution: "bundler",
|
|
576
|
+
types: ["@cloudflare/workers-types", "vitest/globals"],
|
|
577
|
+
strict: true,
|
|
578
|
+
skipLibCheck: true,
|
|
579
|
+
noEmit: true,
|
|
580
|
+
},
|
|
581
|
+
include: ["src/**/*"],
|
|
582
|
+
exclude: ["node_modules"],
|
|
583
|
+
};
|
|
584
|
+
await fs.writeJson(path.join(targetDir, "tsconfig.json"), tsConfig, {
|
|
585
|
+
spaces: 2,
|
|
586
|
+
});
|
|
587
|
+
// 12. Create .gitignore
|
|
588
|
+
const gitignore = `node_modules
|
|
589
|
+
dist
|
|
590
|
+
.wrangler
|
|
591
|
+
.dev.vars
|
|
1192
592
|
`;
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
593
|
+
await fs.writeFile(path.join(targetDir, ".gitignore"), gitignore);
|
|
594
|
+
console.log(chalk.green("ā Created Cloudflare MCP-I template files"));
|
|
595
|
+
console.log(chalk.gray(" - Generated identity keys in .dev.vars"));
|
|
596
|
+
console.log(chalk.gray(" - Configured wrangler.toml with KV namespaces"));
|
|
597
|
+
console.log(chalk.gray(" - Created modular tool structure"));
|
|
598
|
+
console.log(chalk.gray(" - Created setup script for KV namespace creation"));
|
|
599
|
+
// 13. Run npm install first (skip in tests)
|
|
600
|
+
if (!skipCommands) {
|
|
601
|
+
console.log(chalk.blue("\nš¦ Installing dependencies..."));
|
|
602
|
+
await runCommand(packageManager, ["install"], targetDir);
|
|
603
|
+
// 13a. Verify installed version matches expected version
|
|
604
|
+
console.log(chalk.blue("\nš Verifying package versions..."));
|
|
605
|
+
const expectedVersion = "1.5.8-canary.60";
|
|
606
|
+
try {
|
|
607
|
+
const installedPackagePath = path.join(targetDir, "node_modules", "@kya-os", "mcp-i-cloudflare", "package.json");
|
|
608
|
+
if (fs.existsSync(installedPackagePath)) {
|
|
609
|
+
const installedPackage = await fs.readJson(installedPackagePath);
|
|
610
|
+
const installedVersion = installedPackage.version;
|
|
611
|
+
if (installedVersion !== expectedVersion) {
|
|
612
|
+
console.log(chalk.yellow(`\nā ļø Warning: Expected @kya-os/mcp-i-cloudflare@${expectedVersion} but got ${installedVersion}`));
|
|
613
|
+
console.log(chalk.yellow(" This might cause issues with MCP-I handshake. Consider clearing package cache:"));
|
|
614
|
+
if (packageManager === "npm") {
|
|
615
|
+
console.log(chalk.gray(" npm cache clean --force"));
|
|
616
|
+
}
|
|
617
|
+
else if (packageManager === "pnpm") {
|
|
618
|
+
console.log(chalk.gray(" pnpm store prune"));
|
|
619
|
+
}
|
|
620
|
+
else if (packageManager === "yarn") {
|
|
621
|
+
console.log(chalk.gray(" yarn cache clean"));
|
|
622
|
+
}
|
|
623
|
+
console.log(chalk.yellow(" Then reinstall dependencies."));
|
|
624
|
+
}
|
|
625
|
+
else {
|
|
626
|
+
console.log(chalk.green(`ā
@kya-os/mcp-i-cloudflare@${installedVersion} installed correctly`));
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
else {
|
|
630
|
+
console.log(chalk.yellow("ā ļø Could not verify package installation"));
|
|
631
|
+
}
|
|
1201
632
|
}
|
|
1202
|
-
|
|
1203
|
-
console.log(chalk.yellow("ā ļø
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
633
|
+
catch (error) {
|
|
634
|
+
console.log(chalk.yellow("ā ļø Could not verify package versions"));
|
|
635
|
+
if (process.env.DEBUG) {
|
|
636
|
+
console.error(error);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
// 14. Run setup script to create KV namespaces
|
|
640
|
+
console.log(chalk.blue("\nš§ Running setup script to create KV namespaces..."));
|
|
641
|
+
try {
|
|
642
|
+
// Use npm run setup instead of direct node execution to match user's manual workflow
|
|
643
|
+
// This ensures the same environment and PATH resolution as when users run it manually
|
|
644
|
+
await runCommand(packageManager, ["run", "setup"], targetDir);
|
|
645
|
+
console.log(chalk.green("\nā
KV namespaces created successfully!"));
|
|
646
|
+
}
|
|
647
|
+
catch (error) {
|
|
648
|
+
console.log(chalk.yellow("\nā ļø KV namespace setup encountered issues."));
|
|
649
|
+
if (error?.message) {
|
|
650
|
+
console.log(chalk.gray(` Error: ${error.message}`));
|
|
651
|
+
}
|
|
652
|
+
console.log(chalk.yellow("\nYou can run it manually:"));
|
|
653
|
+
console.log(chalk.cyan(` cd ${projectName}`));
|
|
654
|
+
console.log(chalk.cyan(` ${packageManager} run setup`));
|
|
655
|
+
console.log(chalk.gray("\nThe setup script will create all required KV namespaces and update wrangler.toml."));
|
|
1207
656
|
}
|
|
1208
|
-
console.log(chalk.bold("š¦ All KV Namespaces Configured"));
|
|
1209
|
-
console.log(chalk.dim(" - NONCE_CACHE: Replay attack prevention"));
|
|
1210
|
-
console.log(chalk.dim(" - PROOF_ARCHIVE: Cryptographic proof storage"));
|
|
1211
|
-
console.log(chalk.dim(" - IDENTITY_STORAGE: Agent identity persistence"));
|
|
1212
|
-
console.log(chalk.dim(" - DELEGATION_STORAGE: OAuth delegation storage"));
|
|
1213
|
-
console.log(chalk.dim(" - TOOL_PROTECTION_KV: Dashboard-controlled permissions"));
|
|
1214
|
-
console.log();
|
|
1215
|
-
console.log(chalk.cyan(" Run 'npm run kv:create' to create all namespaces"));
|
|
1216
|
-
console.log();
|
|
1217
657
|
}
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
658
|
+
// 15. Final instructions
|
|
659
|
+
console.log(chalk.blue("\n" + "=".repeat(60)));
|
|
660
|
+
console.log(chalk.bold.green("š Cloudflare MCP-I project created successfully!"));
|
|
661
|
+
console.log(chalk.blue("=".repeat(60)));
|
|
662
|
+
console.log(chalk.bold("\nš Important Configuration Notes:"));
|
|
663
|
+
console.log(chalk.gray("\n1. ADMIN_API_KEY (in .dev.vars):"));
|
|
664
|
+
console.log(chalk.gray(" - Set to same value as AGENTSHIELD_API_KEY for convenience"));
|
|
665
|
+
console.log(chalk.gray(" - You can change it if you need separate admin endpoint security"));
|
|
666
|
+
console.log(chalk.gray(" - Required for admin endpoints like /admin/clear-cache\n"));
|
|
667
|
+
console.log(chalk.gray("2. KV Namespaces (in wrangler.toml):"));
|
|
668
|
+
console.log(chalk.gray(" - Required for MCP-I security features"));
|
|
669
|
+
console.log(chalk.gray(" - Auto-created by 'npm run setup' script"));
|
|
670
|
+
console.log(chalk.gray(" - Check wrangler.toml for 'TODO_REPLACE_WITH_ID' if setup failed\n"));
|
|
671
|
+
console.log(chalk.bold("š Next Steps:"));
|
|
672
|
+
console.log(chalk.cyan(" cd " + projectName));
|
|
673
|
+
// Check if they need to run setup
|
|
674
|
+
const wranglerPath = path.join(targetDir, "wrangler.toml");
|
|
675
|
+
if (fs.existsSync(wranglerPath)) {
|
|
676
|
+
const wranglerContent = await fs.readFile(wranglerPath, "utf-8");
|
|
677
|
+
if (wranglerContent.includes("TODO_REPLACE_WITH_ID")) {
|
|
678
|
+
console.log(chalk.yellow(" wrangler login # Login to Cloudflare first!"));
|
|
679
|
+
console.log(chalk.yellow(" npm run setup # Create KV namespaces"));
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
console.log(chalk.cyan(" npm run dev # Start local development"));
|
|
683
|
+
console.log(chalk.cyan(" npm run deploy # Deploy to Cloudflare\n"));
|
|
684
|
+
}
|
|
685
|
+
function toPascalCase(str) {
|
|
686
|
+
const result = str
|
|
687
|
+
.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
|
|
688
|
+
return word.toUpperCase();
|
|
689
|
+
})
|
|
690
|
+
.replace(/\s+/g, "")
|
|
691
|
+
.replace(/-/g, "")
|
|
692
|
+
.replace(/[^a-zA-Z0-9]/g, ""); // Remove all non-alphanumeric characters
|
|
693
|
+
// Fallback to "Project" if result is empty or invalid
|
|
694
|
+
let className = result || "Project";
|
|
695
|
+
// Prefix with underscore if starts with a number (invalid JavaScript identifier)
|
|
696
|
+
if (/^\d/.test(className)) {
|
|
697
|
+
className = "_" + className;
|
|
1221
698
|
}
|
|
699
|
+
return className;
|
|
700
|
+
}
|
|
701
|
+
function runCommand(command, args, cwd) {
|
|
702
|
+
return new Promise((resolve, reject) => {
|
|
703
|
+
const child = spawn(command, args, {
|
|
704
|
+
cwd,
|
|
705
|
+
stdio: "inherit",
|
|
706
|
+
shell: process.platform === "win32",
|
|
707
|
+
});
|
|
708
|
+
child.on("error", reject);
|
|
709
|
+
child.on("exit", (code) => {
|
|
710
|
+
if (code === 0) {
|
|
711
|
+
resolve();
|
|
712
|
+
}
|
|
713
|
+
else {
|
|
714
|
+
reject(new Error(`Command failed with exit code ${code}`));
|
|
715
|
+
}
|
|
716
|
+
});
|
|
717
|
+
});
|
|
1222
718
|
}
|
|
1223
719
|
//# sourceMappingURL=fetch-cloudflare-mcpi-template.js.map
|