@yasad/cli 0.0.0-stage → 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/README.md +22 -2
- package/bin/yasad.mjs +226 -0
- package/lib/check.mjs +114 -0
- package/lib/key.mjs +49 -0
- package/lib/mcp.mjs +270 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# yasad
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Yasad command line. It makes private workspace keys, connects AI agents over MCP and checks apps. No dependencies. Requires Node 24.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npx @yasad/cli init https://YOUR-API-ORIGIN # private key in ~/.yasad + @yasad/client
|
|
7
|
+
npx @yasad/cli mcp add claude # or: codex, vscode, json (Cursor and others)
|
|
8
|
+
npx @yasad/cli check # fails if the app brings its own database
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
| Command | What it does |
|
|
12
|
+
| --- | --- |
|
|
13
|
+
| `yasad init <API_ORIGIN> [ENV_FILE]` | Makes a key and writes it to `ENV_FILE` (default `~/.yasad/workspace.env` in a 0700 folder; the file is never overwritten and is mode 0600 on Linux and macOS). Installs `@yasad/client` when a `package.json` exists. |
|
|
14
|
+
| `yasad key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]` | Makes a key only. Prints the code to approve under Access, or the owner review link when given a workspace connect link. |
|
|
15
|
+
| `yasad mcp [--env FILE]` | Runs the read-only stdio MCP server in-process. It reads only `YASAD_*` (or legacy `FRESH_*`) settings from the file, and an explicit file wins over inherited settings. Set `YASAD_MCP_ALLOW_WRITES=1` (or `FRESH_MCP_ALLOW_WRITES=1`, which new key files use) to allow writes the key permits. |
|
|
16
|
+
| `yasad mcp add <claude\|codex\|vscode\|json> [--env FILE] [--name NAME]` | Registers the server with Claude Code or Codex, or prints config for VS Code (`.vscode/mcp.json`) and other clients (`mcpServers`). Registrations pin this exact CLI version. If the client isn't installed, or on Windows, it prints a safely quoted command and exits 2 without registering anything. |
|
|
17
|
+
| `yasad check [DIR]` | Fails when an app stores business data outside Yasad. |
|
|
18
|
+
|
|
19
|
+
Use `--env FILE` with `npx` rather than exporting `YASAD_API_KEY`: `npx` starts a child process, and Node's `NODE_DEBUG=child_process` would print any exported key. On Windows, `mcp add claude|codex` prints the configuration to add instead of a command line, because cmd and PowerShell quote differently.
|
|
20
|
+
|
|
21
|
+
Key files must live outside every git repository. The CLI refuses any path with a `.git` in an ancestor folder (including nested repositories, symlinks and `..` paths) or inside `GIT_WORK_TREE`/`GIT_DIR`, rather than relying on `.gitignore`. It never edits files in your project.
|
|
22
|
+
|
|
23
|
+
The raw key never leaves your machine; only its SHA-256 digest is approved in the Yasad dashboard. The MCP server, key maker and checker are byte-identical to the `/agent/mcp.mjs`, `/agent/key.mjs` and `/agent/check.mjs` downloads, so either route behaves the same.
|
package/bin/yasad.mjs
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Yasad command line. New first-party code. Node 24, no dependencies.
|
|
3
|
+
// lib/mcp.mjs, lib/key.mjs and lib/check.mjs are byte-identical copies of the hosted
|
|
4
|
+
// /agent/* downloads (tests enforce this), so `npx @yasad/cli` and the downloads behave the same.
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { createInterface } from 'node:readline';
|
|
9
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
10
|
+
import { parseEnv } from 'node:util';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { createBridge, createProtocol } from '../lib/mcp.mjs';
|
|
13
|
+
|
|
14
|
+
const lib = fileURLToPath(new URL('../lib/', import.meta.url));
|
|
15
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
16
|
+
// Outside any project directory, so a key cannot be committed with application code.
|
|
17
|
+
const DEFAULT_ENV = join(homedir(), '.yasad', 'workspace.env');
|
|
18
|
+
const windows = process.platform === 'win32';
|
|
19
|
+
const [command, ...args] = process.argv.slice(2);
|
|
20
|
+
// Node itself honours --env-file and --env-file-if-exists anywhere on the command line, before this
|
|
21
|
+
// script runs, and would
|
|
22
|
+
// apply NODE_OPTIONS from the file. This CLI therefore uses --env and refuses --env-file.
|
|
23
|
+
if (args.some((arg) => /^--env-file(-if-exists)?(=|$)/.test(arg))) {
|
|
24
|
+
console.error('Use --env FILE. Node loads --env-file itself before yasad runs, including any NODE_OPTIONS in it.');
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const help = `yasad ${version}
|
|
29
|
+
|
|
30
|
+
Usage
|
|
31
|
+
npx @yasad/cli init <API_ORIGIN> [ENV_FILE] Make a private key outside your repository, install @yasad/client
|
|
32
|
+
npx @yasad/cli key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]
|
|
33
|
+
Make a private key; prints the code (or review link) to approve
|
|
34
|
+
npx @yasad/cli mcp [--env FILE] Run the MCP server over stdio (read-only unless allowed)
|
|
35
|
+
npx @yasad/cli mcp add <claude|codex|vscode|json> [--env FILE] [--name NAME]
|
|
36
|
+
Connect an AI client to your workspace
|
|
37
|
+
npx @yasad/cli check [DIR] Check that an app stores its data in Yasad
|
|
38
|
+
|
|
39
|
+
ENV_FILE defaults to ${DEFAULT_ENV} and must be outside any git repository. The raw key never leaves this machine; only its digest is approved
|
|
40
|
+
in the Yasad dashboard. Find API_ORIGIN on the dashboard's Connect page.`;
|
|
41
|
+
|
|
42
|
+
function fail(message, code = 1) {
|
|
43
|
+
console.error(message);
|
|
44
|
+
process.exit(code);
|
|
45
|
+
}
|
|
46
|
+
function option(name, fallback) {
|
|
47
|
+
const index = args.indexOf(name);
|
|
48
|
+
if (index === -1) return fallback;
|
|
49
|
+
const value = args[index + 1];
|
|
50
|
+
if (!value || value.startsWith('--')) fail(`${name} needs a value.`);
|
|
51
|
+
args.splice(index, 2);
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
/** Quote one argument for a POSIX shell: nothing inside single quotes is expanded. */
|
|
55
|
+
const sh = (value) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${String(value).replaceAll("'", `'\\''`)}'`);
|
|
56
|
+
const shell = (parts) => parts.map(sh).join(' ');
|
|
57
|
+
function run(script, scriptArgs) {
|
|
58
|
+
const result = spawnSync(process.execPath, [join(lib, script), ...scriptArgs], { stdio: 'inherit' });
|
|
59
|
+
if (result.status !== 0) process.exit(result.status ?? 1);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Read only the Yasad settings from an env file. Everything else in it is ignored, never exported. */
|
|
63
|
+
function readSettings(file) {
|
|
64
|
+
if (!existsSync(file)) fail(`No env file at ${file}. Run \`npx @yasad/cli key\` first.`);
|
|
65
|
+
// Node's own dotenv parser, so quoted and multi-line values are read exactly as Node would.
|
|
66
|
+
const parsed = parseEnv(readFileSync(file, 'utf8')), values = {};
|
|
67
|
+
for (const family of ['YASAD', 'FRESH']) for (const name of ['API_URL', 'API_KEY', 'MCP_ALLOW_WRITES']) {
|
|
68
|
+
if (Object.hasOwn(parsed, `${family}_${name}`)) values[`${family}_${name}`] = parsed[`${family}_${name}`];
|
|
69
|
+
}
|
|
70
|
+
return values;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Choose one settings family. The key and its origin always come from the same family, so a key is
|
|
74
|
+
* never sent to an origin configured for another key. YASAD_* wins over the legacy FRESH_* names.
|
|
75
|
+
*/
|
|
76
|
+
function credentials(source) {
|
|
77
|
+
const set = (name) => (source[name] === undefined || source[name] === '' ? undefined : source[name]);
|
|
78
|
+
const family = set('YASAD_API_KEY') ? 'YASAD' : set('FRESH_API_KEY') ? 'FRESH' : null;
|
|
79
|
+
if (!family) return null;
|
|
80
|
+
return {
|
|
81
|
+
baseUrl: set(`${family}_API_URL`) ?? 'http://127.0.0.1:4310',
|
|
82
|
+
apiKey: set(`${family}_API_KEY`),
|
|
83
|
+
// The write opt-in is not a credential, so either spelling works with any key file.
|
|
84
|
+
allowWrites: (set('YASAD_MCP_ALLOW_WRITES') ?? set('FRESH_MCP_ALLOW_WRITES')) === '1',
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The real location of a key file. The parent is resolved by the operating system from the path as
|
|
90
|
+
* given (a symlink followed by `..` goes where the OS goes, not where string normalization goes), and
|
|
91
|
+
* this one canonical path is used for the repository check, the key writer and the MCP server.
|
|
92
|
+
*/
|
|
93
|
+
function canonical(file) {
|
|
94
|
+
const parent = dirname(file);
|
|
95
|
+
// Without an existing folder the OS cannot resolve symlinks and `..` for us, so refuse to guess.
|
|
96
|
+
if (!existsSync(parent)) fail(`The folder for ${file} does not exist. Create it first (outside any git repository).`);
|
|
97
|
+
return join(realpathSync.native(parent), basename(file));
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Keys never live inside a git repository. Rather than trusting .gitignore (which nested repositories,
|
|
101
|
+
* alternate indexes and pathspec rules can all defeat), refuse any path with a `.git` entry in any
|
|
102
|
+
* ancestor directory, or inside an explicitly configured GIT_WORK_TREE.
|
|
103
|
+
*/
|
|
104
|
+
function outsideRepositories(target) {
|
|
105
|
+
for (let dir = dirname(target); ; dir = dirname(dir)) {
|
|
106
|
+
if (existsSync(join(dir, '.git'))) fail(`${target} is inside the git repository at ${dir}. Keys must live outside repositories; the default is ${DEFAULT_ENV}.`);
|
|
107
|
+
if (dirname(dir) === dir) break;
|
|
108
|
+
}
|
|
109
|
+
// With GIT_DIR or GIT_WORK_TREE set, git's work tree can be anywhere (including core.worktree), so
|
|
110
|
+
// a directory check cannot be trusted. Refuse instead of guessing.
|
|
111
|
+
for (const name of ['GIT_DIR', 'GIT_WORK_TREE']) {
|
|
112
|
+
if (process.env[name]) fail(`${name} is set, so yasad cannot tell which folders git tracks. Unset it and run again.`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** Resolve the key path; the default directory is created privately on first use. */
|
|
116
|
+
function keyPath(file) {
|
|
117
|
+
if (file === DEFAULT_ENV) mkdirSync(dirname(DEFAULT_ENV), { recursive: true, mode: 0o700 });
|
|
118
|
+
const target = canonical(file);
|
|
119
|
+
outsideRepositories(target);
|
|
120
|
+
return target;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The stdio MCP server, run in this process so the key is never placed in a child environment. */
|
|
124
|
+
async function serve(settings) {
|
|
125
|
+
if (!settings) fail('No YASAD_API_KEY found. Pass --env FILE or set YASAD_API_URL and YASAD_API_KEY.');
|
|
126
|
+
const handle = createProtocol(createBridge(settings));
|
|
127
|
+
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
128
|
+
for await (const line of input) {
|
|
129
|
+
if (!line.trim()) continue;
|
|
130
|
+
let response;
|
|
131
|
+
try {
|
|
132
|
+
if (Buffer.byteLength(line) > 65536) throw new Error('oversized');
|
|
133
|
+
response = await handle(JSON.parse(line));
|
|
134
|
+
} catch {
|
|
135
|
+
response = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid JSON message' } };
|
|
136
|
+
}
|
|
137
|
+
if (response) process.stdout.write(JSON.stringify(response) + '\n');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
switch (command) {
|
|
142
|
+
case undefined:
|
|
143
|
+
case 'help':
|
|
144
|
+
case '--help':
|
|
145
|
+
case '-h':
|
|
146
|
+
console.log(help);
|
|
147
|
+
break;
|
|
148
|
+
case '--version':
|
|
149
|
+
case '-v':
|
|
150
|
+
console.log(version);
|
|
151
|
+
break;
|
|
152
|
+
case 'key': {
|
|
153
|
+
const [origin, file = DEFAULT_ENV, ...rest] = args;
|
|
154
|
+
if (!origin) fail('Usage: npx @yasad/cli key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]');
|
|
155
|
+
const target = keyPath(file);
|
|
156
|
+
run('key.mjs', [origin, target, ...rest]);
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
case 'init': {
|
|
160
|
+
const [origin, file = DEFAULT_ENV] = args;
|
|
161
|
+
if (!origin) fail('Usage: npx @yasad/cli init <API_ORIGIN> [ENV_FILE]');
|
|
162
|
+
const target = keyPath(file);
|
|
163
|
+
run('key.mjs', [origin, target]);
|
|
164
|
+
const sdk = `@yasad/client@^${version.split('.').slice(0, 2).join('.')}.0`;
|
|
165
|
+
if (existsSync('package.json')) {
|
|
166
|
+
// Fixed arguments only, so the Windows shell needed for npm.cmd sees no user input.
|
|
167
|
+
const installed = spawnSync(windows ? 'npm.cmd' : 'npm', ['install', sdk], { stdio: 'inherit', shell: windows });
|
|
168
|
+
if (installed.status !== 0) fail(`npm install ${sdk} failed. Install it yourself, then continue.`);
|
|
169
|
+
} else {
|
|
170
|
+
console.log(`No package.json here. Install the SDK in your app with: npm install ${sdk}`);
|
|
171
|
+
}
|
|
172
|
+
console.log(`\nNext: approve the code above in Yasad, then load the key in your server with\n new Yasad({ envFile: ${JSON.stringify(target)} })`);
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
case 'mcp': {
|
|
176
|
+
if (args[0] === 'add') {
|
|
177
|
+
args.shift();
|
|
178
|
+
const client = args.shift();
|
|
179
|
+
// Same OS-resolved path rules as `key`, so the file it created is the file registered.
|
|
180
|
+
const file = canonical(option('--env', DEFAULT_ENV)), name = option('--name', 'yasad');
|
|
181
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) fail('--name may use letters, digits, - and _.');
|
|
182
|
+
if (!existsSync(file)) fail(`No env file at ${file}. Run \`npx @yasad/cli key\` first.`);
|
|
183
|
+
// Pin the exact CLI version so the client never runs a different release than you approved.
|
|
184
|
+
const server = ['npx', '-y', `@yasad/cli@${version}`, 'mcp', '--env', file];
|
|
185
|
+
if (client === 'claude' || client === 'codex') {
|
|
186
|
+
const add = client === 'claude' ? ['mcp', 'add', '--transport', 'stdio', '--scope', 'local', name, '--', ...server] : ['mcp', 'add', name, '--', ...server];
|
|
187
|
+
// Windows agent CLIs are .cmd shims that need a shell, and cmd/PowerShell quote differently,
|
|
188
|
+
// so on Windows print configuration instead of a command line.
|
|
189
|
+
if (windows) {
|
|
190
|
+
// JSON strings are valid TOML basic strings, so paths are escaped correctly for both formats.
|
|
191
|
+
const config = client === 'codex'
|
|
192
|
+
? `Add this to ~/.codex/config.toml:\n[mcp_servers.${name}]\ncommand = ${JSON.stringify(server[0])}\nargs = [${server.slice(1).map((part) => JSON.stringify(part)).join(', ')}]`
|
|
193
|
+
: `Add this to Claude Code's MCP settings (.mcp.json):\n${JSON.stringify({ mcpServers: { [name]: { command: server[0], args: server.slice(1) } } }, null, 2)}`;
|
|
194
|
+
console.log(`Nothing was registered. ${config}`);
|
|
195
|
+
process.exit(2);
|
|
196
|
+
}
|
|
197
|
+
const found = spawnSync(client, ['--version'], { stdio: 'ignore' }).status === 0;
|
|
198
|
+
if (!found) {
|
|
199
|
+
console.log(`${client} was not run (not installed here). Nothing was registered. Run in a POSIX shell:\n ${shell([client, ...add])}`);
|
|
200
|
+
process.exit(2);
|
|
201
|
+
}
|
|
202
|
+
const result = spawnSync(client, add, { stdio: 'inherit' });
|
|
203
|
+
process.exit(result.status ?? 1);
|
|
204
|
+
}
|
|
205
|
+
if (client === 'vscode') {
|
|
206
|
+
console.log(JSON.stringify({ servers: { [name]: { type: 'stdio', command: server[0], args: server.slice(1) } } }, null, 2));
|
|
207
|
+
console.log('\nAdd this to .vscode/mcp.json.');
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
if (client === 'json') {
|
|
211
|
+
console.log(JSON.stringify({ mcpServers: { [name]: { command: server[0], args: server.slice(1) } } }, null, 2));
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
fail('Usage: npx @yasad/cli mcp add <claude|codex|vscode|json> [--env FILE] [--name NAME]');
|
|
215
|
+
}
|
|
216
|
+
const file = option('--env', undefined);
|
|
217
|
+
// An explicitly chosen file wins over inherited settings; it is never merged with them.
|
|
218
|
+
await serve(credentials(file ? readSettings(canonical(file)) : process.env));
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
case 'check':
|
|
222
|
+
run('check.mjs', args);
|
|
223
|
+
break;
|
|
224
|
+
default:
|
|
225
|
+
fail(`Unknown command: ${command}\n\n${help}`);
|
|
226
|
+
}
|
package/lib/check.mjs
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Yasad data check. Run in an app repository: `node check.mjs [project-directory]`.
|
|
3
|
+
// Fails when the app brings its own database or data file instead of storing data in Yasad.
|
|
4
|
+
// Node 24, no dependencies, reads files only. New first-party code.
|
|
5
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
6
|
+
import { join, relative, extname } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
|
|
9
|
+
/** Packages whose purpose is a separate datastore or an ORM for one. */
|
|
10
|
+
export const databasePackages = [
|
|
11
|
+
'better-sqlite3', 'sqlite', 'sqlite3', '@libsql/client', 'sql.js',
|
|
12
|
+
'pg', 'postgres', '@neondatabase/serverless', '@vercel/postgres', 'pg-promise', 'slonik',
|
|
13
|
+
'mysql', 'mysql2', 'mariadb', 'mssql', 'tedious', 'oracledb',
|
|
14
|
+
'mongodb', 'mongoose', 'redis', 'ioredis', '@upstash/redis', '@vercel/kv',
|
|
15
|
+
'prisma', '@prisma/client', 'drizzle-orm', 'knex', 'kysely', 'typeorm', 'sequelize', 'objection',
|
|
16
|
+
'@mikro-orm/core', 'lowdb', 'nedb', '@seald-io/nedb', 'level', 'classic-level', 'lmdb', 'pouchdb',
|
|
17
|
+
'@supabase/supabase-js', 'firebase', 'firebase-admin', '@google-cloud/firestore', '@aws-sdk/client-dynamodb',
|
|
18
|
+
'dexie', 'idb', 'localforage',
|
|
19
|
+
];
|
|
20
|
+
const code = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx', '.py', '.rb', '.go']);
|
|
21
|
+
const skip = new Set(['node_modules', '.git', '.next', 'dist', 'build', 'out', 'coverage', '.turbo', '.vercel']);
|
|
22
|
+
const dataFile = /\.(sqlite3?|db|db3|mdb)$|^schema\.prisma$|^drizzle\.config\.[cm]?[jt]s$|^knexfile\.[cm]?[jt]s$/i;
|
|
23
|
+
/** Append-only record logs (JSON Lines) kept in a data folder. Static .json content such as translations is fine. */
|
|
24
|
+
const dataFolder = /(^|[\\/])(data|db|database|storage|store)[\\/]/i;
|
|
25
|
+
const recordFile = /\.(jsonl|ndjson)$/i;
|
|
26
|
+
/** A write call, in JavaScript or Python. */
|
|
27
|
+
const writeCall = /\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream|json\.dump)\s*\(/;
|
|
28
|
+
/** A data file name in a string literal (often kept in a variable or split across lines). */
|
|
29
|
+
const namedDataFile = /['"`][^'"`\n]*\.(?:json|jsonl|ndjson|csv)['"`]/;
|
|
30
|
+
/** Well-known configuration and build files are not business records. */
|
|
31
|
+
const configFile = /['"`][^'"`\n]*(?:package|package-lock|tsconfig|jsconfig|manifest|vercel|components|composer|app|\.?eslintrc|\.?prettierrc)\.json['"`]/;
|
|
32
|
+
/** A line that only reads a file, such as a build script loading translations. */
|
|
33
|
+
const readCall = /\b(?:readFile|readFileSync|import|require|fetch)\s*\(/;
|
|
34
|
+
const escaped = databasePackages.map((p) => p.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|');
|
|
35
|
+
const sourcePatterns = [
|
|
36
|
+
[new RegExp(`(?:from\\s+|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:node:sqlite|${escaped})(?:/[^'"]*)?['"]`), 'imports a database client'],
|
|
37
|
+
[/\bnew\s+DatabaseSync\s*\(|\bsqlite3\.connect\s*\(|\bcreate_engine\s*\(/, 'opens a database'],
|
|
38
|
+
[/\bCREATE\s+TABLE\b/i, 'defines its own tables'],
|
|
39
|
+
[/\bindexedDB\.open\s*\(/, 'stores records in the browser'],
|
|
40
|
+
[/\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream)\s*\([^)]*\.(?:json|jsonl|ndjson|csv)\b/, 'saves data to a file'],
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
async function* walk(dir, root) {
|
|
44
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
45
|
+
if (entry.name.startsWith('.') && entry.name !== '.env.example' && entry.isDirectory()) continue;
|
|
46
|
+
if (skip.has(entry.name)) continue;
|
|
47
|
+
const path = join(dir, entry.name);
|
|
48
|
+
if (entry.isDirectory()) yield* walk(path, root);
|
|
49
|
+
else if (entry.isFile()) yield path;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @returns {Promise<{file:string,line:number,problem:string,detail:string}[]>} */
|
|
54
|
+
export async function checkProject(root) {
|
|
55
|
+
const findings = [];
|
|
56
|
+
for await (const path of walk(root, root)) {
|
|
57
|
+
const file = relative(root, path) || path;
|
|
58
|
+
const name = path.split(/[\\/]/).pop();
|
|
59
|
+
if (dataFile.test(name)) {
|
|
60
|
+
findings.push({ file, line: 0, problem: 'keeps a separate database or schema file', detail: name });
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (recordFile.test(name) && dataFolder.test(file)) {
|
|
64
|
+
findings.push({ file, line: 0, problem: 'keeps records in a data file', detail: name });
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (name === 'package.json') {
|
|
68
|
+
let pkg;
|
|
69
|
+
try {
|
|
70
|
+
pkg = JSON.parse(await readFile(path, 'utf8'));
|
|
71
|
+
} catch {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
for (const field of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'])
|
|
75
|
+
for (const dep of Object.keys(pkg[field] ?? {}))
|
|
76
|
+
if (databasePackages.includes(dep))
|
|
77
|
+
findings.push({ file, line: 0, problem: 'depends on a database package', detail: dep });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (!code.has(extname(name)) || (await stat(path)).size > 1_000_000) continue;
|
|
81
|
+
const lines = (await readFile(path, 'utf8')).split('\n');
|
|
82
|
+
// A data file named in this file outside a read (often in a variable, or across lines) and written here.
|
|
83
|
+
const namesData = lines.some((text) => namedDataFile.test(text) && !configFile.test(text) && !readCall.test(text));
|
|
84
|
+
lines.forEach((text, i) => {
|
|
85
|
+
let flagged = false;
|
|
86
|
+
for (const [pattern, problem] of sourcePatterns)
|
|
87
|
+
if (pattern.test(text)) {
|
|
88
|
+
findings.push({ file, line: i + 1, problem, detail: text.trim().slice(0, 120) });
|
|
89
|
+
flagged ||= problem === 'saves data to a file';
|
|
90
|
+
}
|
|
91
|
+
if (!flagged && namesData && writeCall.test(text))
|
|
92
|
+
findings.push({ file, line: i + 1, problem: 'saves data to a file', detail: text.trim().slice(0, 120) });
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return findings;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
99
|
+
const root = process.argv[2] ?? '.';
|
|
100
|
+
const findings = await checkProject(root);
|
|
101
|
+
if (!findings.length) {
|
|
102
|
+
console.log('Yasad data check passed: no separate database or data file found.');
|
|
103
|
+
} else {
|
|
104
|
+
console.log('Yasad data check failed. This app stores data outside its Yasad workspace:\n');
|
|
105
|
+
for (const f of findings)
|
|
106
|
+
console.log(` ${f.file}${f.line ? ':' + f.line : ''} ${f.problem}: ${f.detail}`);
|
|
107
|
+
console.log(
|
|
108
|
+
'\nMove this data into Yasad. Use native records where they fit and create a custom collection',
|
|
109
|
+
'\n(createCollection, then createRecord) for everything else. If your credential cannot write,',
|
|
110
|
+
'\nask the owner to approve an operator credential. Then remove the database code and run this check again.',
|
|
111
|
+
);
|
|
112
|
+
process.exitCode = 1;
|
|
113
|
+
}
|
|
114
|
+
}
|
package/lib/key.mjs
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Run on the application server. Only the digest goes into the dashboard.
|
|
2
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
3
|
+
import { writeFile } from 'node:fs/promises';
|
|
4
|
+
const [origin, file] = process.argv.slice(2);
|
|
5
|
+
if (
|
|
6
|
+
!origin ||
|
|
7
|
+
!file ||
|
|
8
|
+
!URL.canParse(origin) ||
|
|
9
|
+
!['http:', 'https:'].includes(new URL(origin).protocol) ||
|
|
10
|
+
new URL(origin).origin !== origin
|
|
11
|
+
) {
|
|
12
|
+
console.error('Usage: node key.mjs API_ORIGIN PRIVATE_ENV_FILE');
|
|
13
|
+
process.exit(1);
|
|
14
|
+
}
|
|
15
|
+
// The optional link carries only a digest and a requested role. The owner approves in Yasad.
|
|
16
|
+
const [approval, kind = 'assistant', name = 'My assistant', role = 'reader', type = 'Other', caller = ''] =
|
|
17
|
+
process.argv.slice(4);
|
|
18
|
+
const url = approval ? new URL(approval) : null;
|
|
19
|
+
if (url) {
|
|
20
|
+
if (
|
|
21
|
+
!['http:', 'https:'].includes(url.protocol) ||
|
|
22
|
+
url.username ||
|
|
23
|
+
url.password ||
|
|
24
|
+
!/^\/w\/[a-f0-9-]{36}\/connect$/.test(url.pathname)
|
|
25
|
+
)
|
|
26
|
+
throw Error('Use the workspace connection address supplied by the owner.');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const key = 'fi_' + randomBytes(32).toString('hex');
|
|
30
|
+
const digest = createHash('sha256').update(key).digest('hex');
|
|
31
|
+
await writeFile(file, 'FRESH_API_URL=' + origin + '\nFRESH_API_KEY=' + key + '\n', {
|
|
32
|
+
mode: 0o600,
|
|
33
|
+
flag: 'wx',
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
if (url) {
|
|
37
|
+
url.search = '';
|
|
38
|
+
url.hash = new URLSearchParams({
|
|
39
|
+
kind,
|
|
40
|
+
name,
|
|
41
|
+
role,
|
|
42
|
+
type,
|
|
43
|
+
caller,
|
|
44
|
+
digest,
|
|
45
|
+
}).toString();
|
|
46
|
+
console.log('Give this review link to the workspace owner:\n' + url.href);
|
|
47
|
+
} else {
|
|
48
|
+
console.log('Register this code under Access → Advanced credential registration.\n' + digest);
|
|
49
|
+
}
|
package/lib/mcp.mjs
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Local stdio MCP adapter. It only consumes the published HTTP contract.
|
|
2
|
+
// No database access, source imports, external dependencies or automatic retries.
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { isIP } from 'node:net';
|
|
6
|
+
// Kept identical to agent/data-policy.mjs (tested). This file is downloaded and run on its own.
|
|
7
|
+
export const dataPolicy =
|
|
8
|
+
'Yasad is the only database for apps built on this workspace. Store every business record and every piece of app state in Yasad: native records (customers, resources, reservations, orders, payments) and custom collections for everything else, such as settings, menus, capacity, notes, statuses and outboxes. Never create or connect another database or data file: no SQLite, PostgreSQL, MySQL, MongoDB, Redis, Prisma, Drizzle, Knex, TypeORM or JSON/CSV files used as storage. If your credential cannot write, ask the owner to approve an operator credential instead of storing data elsewhere. Only secrets (in a private env file) and disposable caches may live outside Yasad. Run /agent/check.mjs on the project before you finish.';
|
|
9
|
+
const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
10
|
+
const readOnlyPost = new Map([
|
|
11
|
+
['availability', '/v1/availability'],
|
|
12
|
+
['getCollection', '/v1/collections/schema'],
|
|
13
|
+
['pageBusinessRecords','/v1/records/page'],
|
|
14
|
+
['queryRecords', '/v1/data/query'],
|
|
15
|
+
['summarizeRecords','/v1/data/summary'],
|
|
16
|
+
]);
|
|
17
|
+
// Keep both the published operation ID and its path pinned for a read-only POST.
|
|
18
|
+
// The standalone adapter also supplies this classification to the REST server.
|
|
19
|
+
export const isReadOperation = (method, path, id) =>
|
|
20
|
+
method === 'GET' || method === 'HEAD' ||
|
|
21
|
+
(method === 'POST' && typeof path === 'string' && readOnlyPost.get(id) === path);
|
|
22
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
23
|
+
const isObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
24
|
+
function origin(raw) {
|
|
25
|
+
const u = new URL(raw);
|
|
26
|
+
if (u.username || u.password || u.search || u.hash || u.pathname !== '/')
|
|
27
|
+
throw new Error('Use a Fresh API origin with no path or credentials');
|
|
28
|
+
const h = u.hostname;
|
|
29
|
+
const local =
|
|
30
|
+
h === 'localhost' ||
|
|
31
|
+
h === '[::1]' ||
|
|
32
|
+
(isIP(h) === 4 &&
|
|
33
|
+
(/^127\./.test(h) ||
|
|
34
|
+
/^10\./.test(h) ||
|
|
35
|
+
/^192\.168\./.test(h) ||
|
|
36
|
+
/^172\.(1[6-9]|2[0-9]|3[01])\./.test(h)));
|
|
37
|
+
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local))
|
|
38
|
+
throw new Error('HTTPS required outside trusted local development');
|
|
39
|
+
return u.origin;
|
|
40
|
+
}
|
|
41
|
+
async function jsonLimited(response) {
|
|
42
|
+
if (!response.body) throw new Error('Empty API response');
|
|
43
|
+
const reader = response.body.getReader();
|
|
44
|
+
let size = 0;
|
|
45
|
+
const chunks = [];
|
|
46
|
+
try {
|
|
47
|
+
for (;;) {
|
|
48
|
+
const { done, value } = await reader.read();
|
|
49
|
+
if (done) break;
|
|
50
|
+
size += value.length;
|
|
51
|
+
if (size > 2_000_000) {
|
|
52
|
+
await reader.cancel();
|
|
53
|
+
throw new Error('API response exceeds local adapter limit');
|
|
54
|
+
}
|
|
55
|
+
chunks.push(Buffer.from(value));
|
|
56
|
+
}
|
|
57
|
+
} finally {
|
|
58
|
+
reader.releaseLock();
|
|
59
|
+
}
|
|
60
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
61
|
+
}
|
|
62
|
+
function toolFailure(code, message, details = {outcome: 'rejected', retryable: false, recovery: 'Review the request and current access.'}) {
|
|
63
|
+
return Object.assign(new Error(message), {safeResult: {error: code, message, ...details}});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function createBridge({ baseUrl, apiKey, allowWrites = false, fetchImpl = fetch }) {
|
|
67
|
+
if (typeof apiKey !== 'string' || !apiKey.trim()) throw new Error('FRESH_API_KEY is required');
|
|
68
|
+
const base = origin(baseUrl);
|
|
69
|
+
async function request(path, method = 'GET', body) {
|
|
70
|
+
const response = await fetchImpl(base + path, {
|
|
71
|
+
method,
|
|
72
|
+
redirect: 'error',
|
|
73
|
+
signal: AbortSignal.timeout(15000),
|
|
74
|
+
headers: {
|
|
75
|
+
authorization: 'Bearer ' + apiKey,
|
|
76
|
+
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
77
|
+
},
|
|
78
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
79
|
+
});
|
|
80
|
+
const data = await jsonLimited(response);
|
|
81
|
+
return { status: response.status, ok: response.ok, data };
|
|
82
|
+
}
|
|
83
|
+
async function discover() {
|
|
84
|
+
const unavailable = () => toolFailure('DISCOVERY_UNAVAILABLE',
|
|
85
|
+
'Yasad could not list the available tools. The requested operation did not start.',
|
|
86
|
+
{outcome: 'rejected', retryable: true, recovery: 'Retry discovery before using the tool.'});
|
|
87
|
+
let caps, contract;
|
|
88
|
+
try {
|
|
89
|
+
[caps, contract] = await Promise.all([request('/v1/capabilities'), request('/openapi.json')]);
|
|
90
|
+
} catch {
|
|
91
|
+
throw unavailable();
|
|
92
|
+
}
|
|
93
|
+
if (caps.status === 401 || caps.status === 403)
|
|
94
|
+
throw toolFailure(caps.status === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN',
|
|
95
|
+
'Workspace discovery was denied. Review this connection before trying again.');
|
|
96
|
+
if (!caps.ok || !contract.ok || !Array.isArray(caps.data?.operations)) throw unavailable();
|
|
97
|
+
const permitted = new Set(caps.data.operations);
|
|
98
|
+
const list = [];
|
|
99
|
+
const routes = new Map();
|
|
100
|
+
for (const [path, methods] of Object.entries(contract.data.paths ?? {})) {
|
|
101
|
+
if (!/^\/v1(?:\/(?:[a-z][a-z-]*|\{id\}))+$/.test(path)) continue;
|
|
102
|
+
for (const [verb, op] of Object.entries(methods)) {
|
|
103
|
+
const name = op.operationId,
|
|
104
|
+
method = verb.toUpperCase(),
|
|
105
|
+
route = [method, path];
|
|
106
|
+
if (
|
|
107
|
+
!['GET', 'POST', 'PATCH', 'DELETE'].includes(method) ||
|
|
108
|
+
typeof name !== 'string' ||
|
|
109
|
+
routes.has(name)
|
|
110
|
+
)
|
|
111
|
+
continue;
|
|
112
|
+
const read = isReadOperation(method, path, name);
|
|
113
|
+
if (!permitted.has(name) || (!allowWrites && !read)) continue;
|
|
114
|
+
|
|
115
|
+
const properties = {},
|
|
116
|
+
required = [];
|
|
117
|
+
if (path.includes('{id}')) {
|
|
118
|
+
properties.id = { type: 'string', pattern: uuid.source };
|
|
119
|
+
required.push('id');
|
|
120
|
+
}
|
|
121
|
+
const body = op.requestBody?.content?.['application/json']?.schema;
|
|
122
|
+
if (body) {
|
|
123
|
+
properties.body = body;
|
|
124
|
+
required.push('body');
|
|
125
|
+
}
|
|
126
|
+
if (method !== 'GET' && !body) continue;
|
|
127
|
+
routes.set(name, route);
|
|
128
|
+
list.push({
|
|
129
|
+
name,
|
|
130
|
+
description:
|
|
131
|
+
op.summary +
|
|
132
|
+
(read
|
|
133
|
+
? ''
|
|
134
|
+
: ' Requires an explicitly supplied stable requestId for retries. No automatic retry.'),
|
|
135
|
+
inputSchema: { type: 'object', properties, required, additionalProperties: false },
|
|
136
|
+
annotations: { readOnlyHint: read },
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return { list, routes };
|
|
141
|
+
}
|
|
142
|
+
async function call(name, args = {}) {
|
|
143
|
+
const { list: available, routes } = await discover();
|
|
144
|
+
const tool = available.find((t) => t.name === name);
|
|
145
|
+
if (!tool) throw toolFailure('OPERATION_UNAVAILABLE','This tool is outside the current connection or write configuration. Review permitted tools before requesting access.');
|
|
146
|
+
if (
|
|
147
|
+
!isObject(args) ||
|
|
148
|
+
Object.keys(args).some((k) => !Object.hasOwn(tool.inputSchema.properties, k)) ||
|
|
149
|
+
tool.inputSchema.required.some((k) => !Object.hasOwn(args, k))
|
|
150
|
+
)
|
|
151
|
+
throw toolFailure('INVALID_INPUT','Invalid tool arguments. Correct the request before submitting it.');
|
|
152
|
+
const [method, template] = routes.get(name);
|
|
153
|
+
let path = template;
|
|
154
|
+
if (template.includes('{id}')) {
|
|
155
|
+
if (typeof args.id !== 'string' || !uuid.test(args.id)) throw toolFailure('INVALID_INPUT','Invalid record UUID. Correct the request before submitting it.');
|
|
156
|
+
path = template.replace('{id}', args.id);
|
|
157
|
+
}
|
|
158
|
+
if (Object.hasOwn(args, 'body') && !isObject(args.body)) throw toolFailure('INVALID_INPUT','Expected body object. Correct the request before submitting it.');
|
|
159
|
+
const read = tool.annotations.readOnlyHint;
|
|
160
|
+
if (!read && !uuid.test(args.body?.requestId ?? ''))
|
|
161
|
+
throw toolFailure('INVALID_INPUT','Explicit lowercase UUID requestId required. Correct the request before submitting it.');
|
|
162
|
+
if (args.body && Buffer.byteLength(JSON.stringify(args.body)) > 32768)
|
|
163
|
+
throw toolFailure('INVALID_INPUT','Request body too large. Correct the request before submitting it.');
|
|
164
|
+
let result;
|
|
165
|
+
try {
|
|
166
|
+
result = await request(path, method, args.body);
|
|
167
|
+
} catch {
|
|
168
|
+
if (read) throw toolFailure('READ_UNAVAILABLE', 'The response could not be read.',
|
|
169
|
+
{outcome: 'read_failed', retryable: true, recovery: 'Try loading this information again.'});
|
|
170
|
+
throw toolFailure('OUTCOME_UNCONFIRMED', 'The outcome of this change could not be confirmed.',
|
|
171
|
+
{outcome: 'unconfirmed', retryable: false, requestId: args.body.requestId,
|
|
172
|
+
recovery: 'Check the original receipt before repeating this change. Keep the same request ID.'});
|
|
173
|
+
}
|
|
174
|
+
if (name === 'getCapabilities' && result.ok) {
|
|
175
|
+
result.data.mcpTools = available.map((t) => t.name);
|
|
176
|
+
result.data.mcpWritesEnabled = allowWrites;
|
|
177
|
+
}
|
|
178
|
+
return { content: [{ type: 'text', text: JSON.stringify(result.data) }], isError: !result.ok };
|
|
179
|
+
}
|
|
180
|
+
return { tools: async () => (await discover()).list, call };
|
|
181
|
+
}
|
|
182
|
+
export function createProtocol(bridge, {stateless = false} = {}) {
|
|
183
|
+
let initialized = stateless;
|
|
184
|
+
return async function handle(message) {
|
|
185
|
+
if (!isObject(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string')
|
|
186
|
+
return { jsonrpc: '2.0', id: message?.id ?? null, error: { code: -32600, message: 'Invalid request' } };
|
|
187
|
+
const { id, method, params } = message;
|
|
188
|
+
if (!Object.hasOwn(message, 'id')) return undefined;
|
|
189
|
+
const success = (result) => ({ jsonrpc: '2.0', id, result });
|
|
190
|
+
const error = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
|
|
191
|
+
if (method === 'initialize') {
|
|
192
|
+
initialized = true;
|
|
193
|
+
const requested = params?.protocolVersion;
|
|
194
|
+
return success({
|
|
195
|
+
protocolVersion: versions.includes(requested) ? requested : versions[0],
|
|
196
|
+
capabilities: { tools: {}, resources: {} },
|
|
197
|
+
serverInfo: { name: stateless ? 'yasad-http' : 'fresh-infra-local', version: '0.1.0' },
|
|
198
|
+
instructions:
|
|
199
|
+
dataPolicy +
|
|
200
|
+
' Read yasad://workspace/context or call getCapabilities to check your workspace, grant and guide links. tools/list reflects your key and local write setting. Persist a requestId before every mutation. Replay the original body and ID after an uncertain outcome.',
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
if (method === 'ping') return success({});
|
|
204
|
+
if (!initialized) return error(-32002, 'Initialize first');
|
|
205
|
+
try {
|
|
206
|
+
if (method === 'resources/list' || method === 'resources/read') {
|
|
207
|
+
const available = await bridge.tools();
|
|
208
|
+
const resources = [
|
|
209
|
+
{uri:'yasad://workspace/context',name:'Workspace and permissions',operation:'getCapabilities'},
|
|
210
|
+
{uri:'yasad://workspace/collections',name:'Business record collections',operation:'listCollections'},
|
|
211
|
+
].filter(r=>available.some(t=>t.name===r.operation));
|
|
212
|
+
if (method==='resources/list') return success({resources:resources.map(({uri,name})=>({uri,name,mimeType:'application/json'}))});
|
|
213
|
+
const entry=resources.find(r=>r.uri===params?.uri);
|
|
214
|
+
if (!entry) return error(-32602,'Resource unavailable for this caller');
|
|
215
|
+
const response=await bridge.call(entry.operation,{});
|
|
216
|
+
if (response.isError) return error(-32002,'Workspace unavailable for this caller');
|
|
217
|
+
return success({contents:[{uri:entry.uri,mimeType:'application/json',text:response.content[0].text}]});
|
|
218
|
+
}
|
|
219
|
+
if (method === 'tools/list') return success({ tools: await bridge.tools() });
|
|
220
|
+
if (method === 'tools/call') {
|
|
221
|
+
try {
|
|
222
|
+
return success(await bridge.call(params?.name, params?.arguments ?? {}));
|
|
223
|
+
} catch (error) {
|
|
224
|
+
const result = error.safeResult ?? {error: 'OUTCOME_UNCONFIRMED',
|
|
225
|
+
message: 'Yasad could not confirm the tool response.', outcome: 'unconfirmed', retryable: false,
|
|
226
|
+
recovery: 'Check the original receipt before repeating any change. Keep the same request ID.'};
|
|
227
|
+
return success({isError:true,content:[{type:'text',text:JSON.stringify(result)}]});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return error(-32601, 'Method not found');
|
|
231
|
+
} catch {
|
|
232
|
+
return error(-32000, 'Fresh API unavailable or discovery failed');
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
class CredentialPairError extends Error {}
|
|
237
|
+
|
|
238
|
+
export function standaloneBridge(env, fetchImpl = fetch) {
|
|
239
|
+
const family = env.YASAD_API_KEY !== undefined ? 'YASAD' : 'FRESH';
|
|
240
|
+
const apiKey = env[family + '_API_KEY'];
|
|
241
|
+
const baseUrl = env[family + '_API_URL'];
|
|
242
|
+
if (!apiKey?.trim() || !baseUrl?.trim())
|
|
243
|
+
throw new CredentialPairError('Set ' + family + '_API_KEY and ' + family + '_API_URL together before starting MCP.');
|
|
244
|
+
return createBridge({ baseUrl, apiKey, allowWrites: env[family + '_MCP_ALLOW_WRITES'] === '1', fetchImpl });
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (!process.env.YASAD_BUNDLED && process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
248
|
+
try {
|
|
249
|
+
const bridge = standaloneBridge(process.env);
|
|
250
|
+
const handle = createProtocol(bridge);
|
|
251
|
+
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
252
|
+
for await (const line of input) {
|
|
253
|
+
if (!line.trim()) continue;
|
|
254
|
+
let response;
|
|
255
|
+
try {
|
|
256
|
+
if (Buffer.byteLength(line) > 65536) throw new Error('oversized');
|
|
257
|
+
response = await handle(JSON.parse(line));
|
|
258
|
+
} catch {
|
|
259
|
+
response = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid JSON message' } };
|
|
260
|
+
}
|
|
261
|
+
if (response) process.stdout.write(JSON.stringify(response) + '\n');
|
|
262
|
+
}
|
|
263
|
+
} catch (error) {
|
|
264
|
+
const message = error instanceof CredentialPairError
|
|
265
|
+
? error.message
|
|
266
|
+
: 'Fresh MCP startup failed; check server environment.';
|
|
267
|
+
process.stderr.write(message + '\n');
|
|
268
|
+
process.exitCode = 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yasad/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Yasad command line: create a workspace key, connect AI agents over MCP and check an app.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"yasadInfra": {
|
|
8
|
+
"layer": "integration",
|
|
9
|
+
"provides": "cli"
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=24"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"yasad",
|
|
16
|
+
"cli",
|
|
17
|
+
"mcp"
|
|
18
|
+
],
|
|
19
|
+
"bin": {
|
|
20
|
+
"yasad": "bin/yasad.mjs"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"bin",
|
|
24
|
+
"lib",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "node --check bin/yasad.mjs && node --check lib/mcp.mjs && node --check lib/key.mjs && node --check lib/check.mjs"
|
|
29
|
+
},
|
|
30
|
+
"sideEffects": true,
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
}
|
|
34
|
+
}
|