@codapult/cli 0.15.3 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +107 -3
  2. package/dist/commands/config-show.js +6 -32
  3. package/dist/commands/db.d.ts +2 -0
  4. package/dist/commands/db.js +81 -2
  5. package/dist/commands/deploy.js +44 -17
  6. package/dist/commands/doctor.d.ts +1 -1
  7. package/dist/commands/doctor.js +9 -234
  8. package/dist/commands/env.js +21 -17
  9. package/dist/commands/mcp.d.ts +5 -0
  10. package/dist/commands/mcp.js +98 -0
  11. package/dist/commands/plugins.js +40 -5
  12. package/dist/commands/setup.js +2 -2
  13. package/dist/index.js +24 -5
  14. package/dist/mcp/resources.js +34 -3
  15. package/dist/mcp/server.js +4 -1
  16. package/dist/mcp/tools/db.js +185 -49
  17. package/dist/mcp/tools/db.test.js +59 -7
  18. package/dist/mcp/tools/env.d.ts +7 -0
  19. package/dist/mcp/tools/env.js +96 -2
  20. package/dist/mcp/tools/env.test.js +4 -2
  21. package/dist/mcp/tools/generate.js +64 -10
  22. package/dist/mcp/tools/plugins.js +125 -13
  23. package/dist/mcp/tools/project.js +59 -46
  24. package/dist/mcp/tools/project.test.js +20 -8
  25. package/dist/utils/check-report.d.ts +18 -0
  26. package/dist/utils/check-report.js +30 -0
  27. package/dist/utils/command.d.ts +18 -0
  28. package/dist/utils/command.js +29 -0
  29. package/dist/utils/config-report.d.ts +12 -0
  30. package/dist/utils/config-report.js +41 -0
  31. package/dist/utils/config-report.test.d.ts +1 -0
  32. package/dist/utils/config-report.test.js +20 -0
  33. package/dist/utils/db-diff.d.ts +11 -0
  34. package/dist/utils/db-diff.js +37 -0
  35. package/dist/utils/env-compatibility.d.ts +10 -0
  36. package/dist/utils/env-compatibility.js +52 -0
  37. package/dist/utils/env-compatibility.test.d.ts +1 -0
  38. package/dist/utils/env-compatibility.test.js +23 -0
  39. package/dist/utils/env-config.d.ts +9 -0
  40. package/dist/utils/env-config.js +116 -4
  41. package/dist/utils/env-schema-parser.d.ts +2 -0
  42. package/dist/utils/env-schema-parser.js +32 -0
  43. package/dist/utils/env-schema-parser.test.d.ts +1 -0
  44. package/dist/utils/env-schema-parser.test.js +11 -0
  45. package/dist/utils/health-render.d.ts +3 -0
  46. package/dist/utils/health-render.js +28 -0
  47. package/dist/utils/health-render.test.d.ts +1 -0
  48. package/dist/utils/health-render.test.js +18 -0
  49. package/dist/utils/health.d.ts +26 -0
  50. package/dist/utils/health.js +249 -0
  51. package/dist/utils/live-db-diff.d.ts +17 -0
  52. package/dist/utils/live-db-diff.js +131 -0
  53. package/dist/utils/live-db-diff.test.d.ts +1 -0
  54. package/dist/utils/live-db-diff.test.js +29 -0
  55. package/dist/utils/manifest.d.ts +1 -0
  56. package/dist/utils/patchers.d.ts +2 -0
  57. package/dist/utils/patchers.js +25 -13
  58. package/dist/utils/patchers.test.js +41 -7
  59. package/dist/utils/schema-parity.d.ts +15 -0
  60. package/dist/utils/schema-parity.js +91 -0
  61. package/dist/utils/schema-parity.test.d.ts +1 -0
  62. package/dist/utils/schema-parity.test.js +27 -0
  63. package/dist/utils/schema-parser.d.ts +12 -0
  64. package/dist/utils/schema-parser.js +130 -0
  65. package/dist/utils/schema-parser.test.d.ts +1 -0
  66. package/dist/utils/schema-parser.test.js +59 -0
  67. package/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
3
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
4
  import { registerProjectTools } from './tools/project.js';
@@ -8,9 +9,11 @@ import { registerGenerateTools } from './tools/generate.js';
8
9
  import { registerDeployTools } from './tools/deploy.js';
9
10
  import { registerPrompts } from './prompts.js';
10
11
  import { registerResources } from './resources.js';
12
+ const require = createRequire(import.meta.url);
13
+ const packageJson = require('../../package.json');
11
14
  const server = new McpServer({
12
15
  name: 'codapult',
13
- version: '0.1.0',
16
+ version: packageJson.version,
14
17
  });
15
18
  registerProjectTools(server);
16
19
  registerDbTools(server);
@@ -3,63 +3,112 @@ import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { findProjectRoot, readProjectFile } from '../../utils/project.js';
5
5
  import { getProjectEnvOptions, loadProjectEnv } from '../../utils/project-env.js';
6
+ import { getAdapters } from '../../utils/env-config.js';
6
7
  import { envSourceSchema } from './schemas.js';
8
+ import { commandResponse, runProjectCommand } from '../../utils/command.js';
9
+ import { previewMigration } from '../../utils/db-diff.js';
10
+ import { parseDatabaseSchema } from '../../utils/schema-parser.js';
11
+ import { compareSchemaFiles } from '../../utils/schema-parity.js';
12
+ import { diffSchemaWithLiveDatabase, inspectLiveDatabase } from '../../utils/live-db-diff.js';
7
13
  function getRoot() {
8
14
  const root = findProjectRoot();
9
15
  if (!root)
10
16
  throw new Error('Not inside a Codapult project');
11
17
  return root;
12
18
  }
13
- function parseSchema(content) {
14
- const tables = [];
15
- const tableRegex = /export\s+const\s+(\w+)\s*=\s*(?:sqliteTable|pgTable)\(\s*['"](\w+)['"]\s*,\s*\{/g;
16
- let match;
17
- while ((match = tableRegex.exec(content)) != null) {
18
- const tableName = match[2];
19
- const startIdx = match.index + match[0].length;
20
- let depth = 1;
21
- let endIdx = startIdx;
22
- for (let i = startIdx; i < content.length && depth > 0; i += 1) {
23
- if (content[i] === '{')
24
- depth += 1;
25
- if (content[i] === '}')
26
- depth -= 1;
27
- endIdx = i;
28
- }
29
- const body = content.slice(startIdx, endIdx);
30
- const columns = [];
31
- const colRegex = /(\w+)\s*:\s*(text|integer|real|blob|boolean|timestamp|serial)\(['"](\w+)['"]/g;
32
- let colMatch;
33
- while ((colMatch = colRegex.exec(body)) != null) {
34
- const colName = colMatch[1];
35
- const colType = colMatch[2];
36
- const constraints = [];
37
- const lineEnd = body.indexOf('\n', colMatch.index + colMatch[0].length);
38
- const restOfLine = body.slice(colMatch.index, lineEnd > -1 ? lineEnd : undefined);
39
- if (restOfLine.includes('.primaryKey()'))
40
- constraints.push('PRIMARY KEY');
41
- if (restOfLine.includes('.notNull()'))
42
- constraints.push('NOT NULL');
43
- if (restOfLine.includes('.unique()'))
44
- constraints.push('UNIQUE');
45
- if (restOfLine.includes('.references('))
46
- constraints.push('FK');
47
- if (restOfLine.includes('.$defaultFn('))
48
- constraints.push('DEFAULT');
49
- columns.push({ name: colName, type: colType, constraints });
50
- }
51
- tables.push({ name: tableName, columns });
52
- }
53
- return tables;
19
+ function getDatabaseContext(root, envSource) {
20
+ const envContent = loadProjectEnv(root, getProjectEnvOptions(envSource)).content;
21
+ const provider = getAdapters(envContent).database;
22
+ return {
23
+ provider,
24
+ schemaPath: provider === 'postgres' ? 'src/lib/db/schema-pg.ts' : 'src/lib/db/schema.ts',
25
+ };
54
26
  }
27
+ const parseSchema = parseDatabaseSchema;
55
28
  export function registerDbTools(server) {
29
+ server.registerTool('codapult_db_generate', {
30
+ title: 'Generate Database Migration',
31
+ description: 'Generate a database migration from the current Drizzle schema',
32
+ inputSchema: {
33
+ dry_run: z.boolean().default(false).describe('Preview without changing files'),
34
+ },
35
+ }, ({ dry_run }) => {
36
+ const root = getRoot();
37
+ const { provider } = getDatabaseContext(root);
38
+ if (dry_run) {
39
+ const preview = previewMigration(root, provider, getDatabaseContext(root).schemaPath);
40
+ return {
41
+ content: [{ type: 'text', text: JSON.stringify(preview, null, 2) }],
42
+ isError: !preview.command.passed,
43
+ };
44
+ }
45
+ return commandResponse(runProjectCommand('pnpm db:generate', root, {
46
+ env: provider === 'postgres' ? { DB_PROVIDER: 'postgres' } : undefined,
47
+ }));
48
+ });
49
+ server.registerTool('codapult_db_migration_diff', {
50
+ title: 'Preview Database Migration',
51
+ description: 'Generate the pending SQL migration in a temporary directory without changing project files. Compares source schema with local migration history, not the live database.',
52
+ inputSchema: {},
53
+ }, () => {
54
+ const root = getRoot();
55
+ const { provider, schemaPath } = getDatabaseContext(root);
56
+ const preview = previewMigration(root, provider, schemaPath);
57
+ return {
58
+ content: [{ type: 'text', text: JSON.stringify(preview, null, 2) }],
59
+ isError: !preview.command.passed,
60
+ };
61
+ });
62
+ server.registerTool('codapult_db_push', {
63
+ title: 'Push Database Schema',
64
+ description: 'Apply the current Drizzle schema to the configured database',
65
+ inputSchema: {
66
+ dry_run: z.boolean().default(false).describe('Preview without changing the database'),
67
+ },
68
+ }, ({ dry_run }) => {
69
+ const root = getRoot();
70
+ const { provider } = getDatabaseContext(root);
71
+ if (dry_run) {
72
+ return {
73
+ content: [
74
+ {
75
+ type: 'text',
76
+ text: JSON.stringify({ dryRun: true, command: 'pnpm db:push', provider }, null, 2),
77
+ },
78
+ ],
79
+ };
80
+ }
81
+ return commandResponse(runProjectCommand('pnpm db:push', root, {
82
+ env: provider === 'postgres' ? { DB_PROVIDER: 'postgres' } : undefined,
83
+ }));
84
+ });
85
+ server.registerTool('codapult_db_seed', {
86
+ title: 'Seed Database',
87
+ description: 'Run the project database seed script',
88
+ inputSchema: {
89
+ dry_run: z.boolean().default(false).describe('Preview without changing the database'),
90
+ },
91
+ }, ({ dry_run }) => {
92
+ if (dry_run) {
93
+ return {
94
+ content: [
95
+ {
96
+ type: 'text',
97
+ text: JSON.stringify({ dryRun: true, command: 'pnpm db:seed' }, null, 2),
98
+ },
99
+ ],
100
+ };
101
+ }
102
+ return commandResponse(runProjectCommand('pnpm db:seed', getRoot()));
103
+ });
56
104
  server.registerTool('codapult_db_get_tables', {
57
105
  title: 'Get Database Tables',
58
106
  description: 'List all tables in the database schema with column counts',
59
107
  inputSchema: {},
60
108
  }, () => {
61
109
  const root = getRoot();
62
- const content = readProjectFile(root, 'src/lib/db/schema.ts');
110
+ const { provider, schemaPath } = getDatabaseContext(root);
111
+ const content = readProjectFile(root, schemaPath);
63
112
  if (!content)
64
113
  return {
65
114
  content: [{ type: 'text', text: 'Schema file not found' }],
@@ -71,7 +120,14 @@ export function registerDbTools(server) {
71
120
  columns: t.columns.length,
72
121
  columnNames: t.columns.map((c) => c.name),
73
122
  }));
74
- return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] };
123
+ return {
124
+ content: [
125
+ {
126
+ type: 'text',
127
+ text: JSON.stringify({ provider, schemaPath, tables: summary }, null, 2),
128
+ },
129
+ ],
130
+ };
75
131
  });
76
132
  server.registerTool('codapult_db_get_table_info', {
77
133
  title: 'Get Table Info',
@@ -81,7 +137,8 @@ export function registerDbTools(server) {
81
137
  },
82
138
  }, ({ table }) => {
83
139
  const root = getRoot();
84
- const content = readProjectFile(root, 'src/lib/db/schema.ts');
140
+ const { provider, schemaPath } = getDatabaseContext(root);
141
+ const content = readProjectFile(root, schemaPath);
85
142
  if (!content)
86
143
  return {
87
144
  content: [{ type: 'text', text: 'Schema file not found' }],
@@ -98,7 +155,14 @@ export function registerDbTools(server) {
98
155
  isError: true,
99
156
  };
100
157
  }
101
- return { content: [{ type: 'text', text: JSON.stringify(found, null, 2) }] };
158
+ return {
159
+ content: [
160
+ {
161
+ type: 'text',
162
+ text: JSON.stringify({ provider, schemaPath, ...found }, null, 2),
163
+ },
164
+ ],
165
+ };
102
166
  });
103
167
  server.registerTool('codapult_db_status', {
104
168
  title: 'Database Status',
@@ -109,9 +173,9 @@ export function registerDbTools(server) {
109
173
  }, ({ env_source }) => {
110
174
  const root = getRoot();
111
175
  const envContent = loadProjectEnv(root, getProjectEnvOptions(env_source)).content;
112
- const providerMatch = /^DB_PROVIDER\s*=\s*"?(\w+)"?/m.exec(envContent);
113
- const provider = providerMatch?.[1] ?? 'turso';
114
- const schemaContent = readProjectFile(root, 'src/lib/db/schema.ts') ?? '';
176
+ const provider = getAdapters(envContent).database;
177
+ const schemaPath = provider === 'postgres' ? 'src/lib/db/schema-pg.ts' : 'src/lib/db/schema.ts';
178
+ const schemaContent = readProjectFile(root, schemaPath) ?? '';
115
179
  const tables = parseSchema(schemaContent);
116
180
  let sqliteMigrations = 0;
117
181
  let pgMigrations = 0;
@@ -123,7 +187,79 @@ export function registerDbTools(server) {
123
187
  if (existsSync(migrPgDir)) {
124
188
  pgMigrations = readdirSync(migrPgDir).filter((f) => f.endsWith('.sql')).length;
125
189
  }
126
- const result = { provider, tableCount: tables.length, sqliteMigrations, pgMigrations };
190
+ const result = {
191
+ provider,
192
+ schemaPath,
193
+ migrationsPath: provider === 'postgres' ? 'src/lib/db/migrations-pg' : 'src/lib/db/migrations',
194
+ tableCount: tables.length,
195
+ sqliteMigrations,
196
+ pgMigrations,
197
+ };
127
198
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
128
199
  });
200
+ server.registerTool('codapult_db_live_diff', {
201
+ title: 'Compare Schema With Live Database',
202
+ description: 'Read-only comparison of the active Drizzle schema with the configured live database. Runs only catalog queries; never executes DDL or migration commands.',
203
+ inputSchema: {
204
+ env_source: envSourceSchema.optional(),
205
+ },
206
+ }, ({ env_source }) => {
207
+ const root = getRoot();
208
+ const { provider, schemaPath } = getDatabaseContext(root, env_source);
209
+ const schema = parseSchema(readProjectFile(root, schemaPath) ?? '');
210
+ try {
211
+ const envContent = loadProjectEnv(root, getProjectEnvOptions(env_source)).content;
212
+ const database = inspectLiveDatabase(root, envContent);
213
+ const differences = diffSchemaWithLiveDatabase(schema, database);
214
+ return {
215
+ content: [
216
+ {
217
+ type: 'text',
218
+ text: JSON.stringify({
219
+ provider,
220
+ schemaPath,
221
+ readOnly: true,
222
+ identical: differences.length === 0,
223
+ status: differences.length > 0 ? 'fail' : 'ok',
224
+ differences,
225
+ }, null, 2),
226
+ },
227
+ ],
228
+ };
229
+ }
230
+ catch (error) {
231
+ return {
232
+ content: [
233
+ {
234
+ type: 'text',
235
+ text: error instanceof Error ? error.message : 'Live database inspection failed',
236
+ },
237
+ ],
238
+ isError: true,
239
+ };
240
+ }
241
+ });
242
+ server.registerTool('codapult_db_schema_diff', {
243
+ title: 'Compare Database Schemas',
244
+ description: 'Compare SQLite and PostgreSQL schema files and report missing tables, columns, and type differences',
245
+ inputSchema: {},
246
+ }, () => {
247
+ const root = getRoot();
248
+ const sqlitePath = 'src/lib/db/schema.ts';
249
+ const postgresPath = 'src/lib/db/schema-pg.ts';
250
+ const report = compareSchemaFiles(parseSchema(readProjectFile(root, sqlitePath) ?? ''), parseSchema(readProjectFile(root, postgresPath) ?? ''));
251
+ return {
252
+ content: [
253
+ {
254
+ type: 'text',
255
+ text: JSON.stringify({
256
+ ...report,
257
+ sqlitePath,
258
+ postgresPath,
259
+ }, null, 2),
260
+ },
261
+ ],
262
+ isError: report.status === 'fail',
263
+ };
264
+ });
129
265
  }
@@ -25,14 +25,20 @@ function createMockServer() {
25
25
  return { registerTool, tools };
26
26
  }
27
27
  describe('registerDbTools', () => {
28
- it('registers 3 DB tools', () => {
28
+ it('registers database inspection and mutation tools', () => {
29
29
  const server = createMockServer();
30
30
  registerDbTools(server);
31
- expect(server.tools).toHaveLength(3);
31
+ expect(server.tools).toHaveLength(9);
32
32
  expect(server.tools.map((t) => t.name)).toEqual([
33
+ 'codapult_db_generate',
34
+ 'codapult_db_migration_diff',
35
+ 'codapult_db_push',
36
+ 'codapult_db_seed',
33
37
  'codapult_db_get_tables',
34
38
  'codapult_db_get_table_info',
35
39
  'codapult_db_status',
40
+ 'codapult_db_live_diff',
41
+ 'codapult_db_schema_diff',
36
42
  ]);
37
43
  });
38
44
  describe('codapult_db_get_tables', () => {
@@ -58,11 +64,13 @@ export const post = sqliteTable('post', {
58
64
  const handler = server.tools.find((t) => t.name === 'codapult_db_get_tables').handler;
59
65
  const result = handler({});
60
66
  const parsed = JSON.parse(result.content[0].text);
61
- expect(parsed).toHaveLength(2);
62
- expect(parsed[0].name).toBe('user');
63
- expect(parsed[0].columns).toBe(3);
64
- expect(parsed[1].name).toBe('post');
65
- expect(parsed[1].columns).toBe(3);
67
+ expect(parsed.provider).toBe('turso');
68
+ expect(parsed.schemaPath).toBe('src/lib/db/schema.ts');
69
+ expect(parsed.tables).toHaveLength(2);
70
+ expect(parsed.tables[0].name).toBe('user');
71
+ expect(parsed.tables[0].columns).toBe(3);
72
+ expect(parsed.tables[1].name).toBe('post');
73
+ expect(parsed.tables[1].columns).toBe(3);
66
74
  });
67
75
  it('returns error when schema file not found', () => {
68
76
  const server = createMockServer();
@@ -166,4 +174,48 @@ export const user = sqliteTable('user', {
166
174
  expect(parsed.provider).toBe('postgres');
167
175
  });
168
176
  });
177
+ describe('codapult_db_schema_diff', () => {
178
+ it('returns an ok parity report for matching schemas', () => {
179
+ const server = createMockServer();
180
+ registerDbTools(server);
181
+ const sqlite = `export const user = sqliteTable('user', { id: text('id') });`;
182
+ const postgres = `export const user = pgTable('user', { id: text('id') });`;
183
+ mockedReadProject.mockImplementation((_root, path) => {
184
+ if (path === 'src/lib/db/schema.ts')
185
+ return sqlite;
186
+ if (path === 'src/lib/db/schema-pg.ts')
187
+ return postgres;
188
+ return undefined;
189
+ });
190
+ const handler = server.tools.find((t) => t.name === 'codapult_db_schema_diff').handler;
191
+ const result = handler({});
192
+ const parsed = JSON.parse(result.content[0].text);
193
+ expect(result.isError).toBe(false);
194
+ expect(parsed.status).toBe('ok');
195
+ expect(parsed.identical).toBe(true);
196
+ expect(parsed.differences).toEqual([]);
197
+ });
198
+ it('returns an error result for missing tables', () => {
199
+ const server = createMockServer();
200
+ registerDbTools(server);
201
+ mockedReadProject.mockImplementation((_root, path) => {
202
+ if (path === 'src/lib/db/schema.ts') {
203
+ return `export const user = sqliteTable('user', { id: text('id') });`;
204
+ }
205
+ if (path === 'src/lib/db/schema-pg.ts') {
206
+ return `export const post = pgTable('post', { id: text('id') });`;
207
+ }
208
+ return undefined;
209
+ });
210
+ const handler = server.tools.find((t) => t.name === 'codapult_db_schema_diff').handler;
211
+ const result = handler({});
212
+ const parsed = JSON.parse(result.content[0].text);
213
+ expect(result.isError).toBe(true);
214
+ expect(parsed.status).toBe('fail');
215
+ expect(parsed.differences.map((difference) => difference.issue)).toEqual([
216
+ 'missing_in_postgres',
217
+ 'missing_in_sqlite',
218
+ ]);
219
+ });
220
+ });
169
221
  });
@@ -1,2 +1,9 @@
1
1
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export interface EnvEntry {
3
+ key: string;
4
+ value: string;
5
+ comment?: string;
6
+ required: boolean;
7
+ }
8
+ export declare function parseEnvFile(content: string): EnvEntry[];
2
9
  export declare function registerEnvTools(server: McpServer): void;
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { findProjectRoot, readProjectFile } from '../../utils/project.js';
5
5
  import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME, getProjectEnvOptions, loadProjectEnv, } from '../../utils/project-env.js';
6
+ import { findProviderIssues, getAdapters, getAuthMethods, getFeatures, getOauthProviders, readEnv, } from '../../utils/env-config.js';
6
7
  import { envSourceSchema } from './schemas.js';
7
8
  function getRoot() {
8
9
  const root = findProjectRoot();
@@ -10,7 +11,7 @@ function getRoot() {
10
11
  throw new Error('Not inside a Codapult project');
11
12
  return root;
12
13
  }
13
- function parseEnvFile(content) {
14
+ export function parseEnvFile(content) {
14
15
  const entries = [];
15
16
  let lastComment = '';
16
17
  for (const line of content.split('\n')) {
@@ -45,7 +46,95 @@ function maskValue(value) {
45
46
  return value.slice(0, 4) + '****';
46
47
  }
47
48
  const ENV_KEY_REGEX = /^[A-Z][A-Z0-9_]*$/;
49
+ function getEffectiveConfig(content) {
50
+ return {
51
+ appMode: readEnv(content, 'APP_MODE', 'app'),
52
+ adapters: getAdapters(content),
53
+ authMethods: getAuthMethods(content),
54
+ oauthProviders: getOauthProviders(content),
55
+ features: getFeatures(content),
56
+ };
57
+ }
48
58
  export function registerEnvTools(server) {
59
+ server.registerTool('codapult_env_check', {
60
+ title: 'Check Environment',
61
+ description: `Validate ${ENV_FILE_NAME} against ${ENV_EXAMPLE_FILE_NAME} without exposing secret values`,
62
+ inputSchema: { env_source: envSourceSchema.optional() },
63
+ }, ({ env_source }) => {
64
+ const root = getRoot();
65
+ const example = parseEnvFile(readProjectFile(root, ENV_EXAMPLE_FILE_NAME) ?? '');
66
+ const local = parseEnvFile(loadProjectEnv(root, getProjectEnvOptions(env_source)).content);
67
+ const localKeys = new Set(local.map((entry) => entry.key));
68
+ const missing = example
69
+ .filter((entry) => entry.required && !localKeys.has(entry.key))
70
+ .map((entry) => entry.key);
71
+ const unconfigured = local
72
+ .filter((entry) => !entry.value || /^(your-|generate-|https?:\/\/your|""?)/.test(entry.value))
73
+ .map((entry) => entry.key);
74
+ const extra = local
75
+ .filter((entry) => !example.some((candidate) => candidate.key === entry.key))
76
+ .map((entry) => entry.key);
77
+ const envContent = loadProjectEnv(root, getProjectEnvOptions(env_source)).content;
78
+ const providerIssues = findProviderIssues(envContent);
79
+ return {
80
+ content: [
81
+ {
82
+ type: 'text',
83
+ text: JSON.stringify({
84
+ valid: providerIssues.every((issue) => issue.severity !== 'error'),
85
+ missing,
86
+ unconfigured,
87
+ extra,
88
+ providerIssues,
89
+ effective: getEffectiveConfig(envContent),
90
+ }, null, 2),
91
+ },
92
+ ],
93
+ };
94
+ });
95
+ server.registerTool('codapult_env_sync', {
96
+ title: 'Sync Environment',
97
+ description: `Add missing variables from ${ENV_EXAMPLE_FILE_NAME} to ${ENV_FILE_NAME}`,
98
+ inputSchema: {
99
+ dry_run: z
100
+ .boolean()
101
+ .default(false)
102
+ .describe('Preview missing variables without writing the file'),
103
+ },
104
+ }, ({ dry_run }) => {
105
+ const root = getRoot();
106
+ const exampleContent = readProjectFile(root, ENV_EXAMPLE_FILE_NAME);
107
+ if (!exampleContent) {
108
+ return {
109
+ content: [{ type: 'text', text: `${ENV_EXAMPLE_FILE_NAME} not found` }],
110
+ isError: true,
111
+ };
112
+ }
113
+ const envPath = resolve(root, ENV_FILE_NAME);
114
+ const fileExisted = existsSync(envPath);
115
+ const currentContent = fileExisted ? readFileSync(envPath, 'utf-8') : '';
116
+ const currentKeys = new Set(parseEnvFile(currentContent).map((entry) => entry.key));
117
+ const missing = parseEnvFile(exampleContent).filter((entry) => entry.required && !currentKeys.has(entry.key));
118
+ if (!dry_run && !existsSync(envPath))
119
+ writeFileSync(envPath, exampleContent, 'utf-8');
120
+ else if (!dry_run && missing.length > 0) {
121
+ const additions = missing.map((entry) => `${entry.key}=${entry.value}`).join('\n');
122
+ writeFileSync(envPath, `${currentContent.trimEnd()}\n${additions}\n`, 'utf-8');
123
+ }
124
+ return {
125
+ content: [
126
+ {
127
+ type: 'text',
128
+ text: JSON.stringify({
129
+ dryRun: dry_run,
130
+ created: !dry_run && !fileExisted,
131
+ added: missing.map((entry) => entry.key),
132
+ path: ENV_FILE_NAME,
133
+ }, null, 2),
134
+ },
135
+ ],
136
+ };
137
+ });
49
138
  server.registerTool('codapult_env_schema', {
50
139
  title: 'Env Schema',
51
140
  description: `Get all environment variables from ${ENV_EXAMPLE_FILE_NAME} with descriptions and default values`,
@@ -100,7 +189,12 @@ export function registerEnvTools(server) {
100
189
  variables,
101
190
  missing,
102
191
  unconfigured,
103
- ...(show_secrets ? { warning: 'Sensitive values are shown in plain text' } : {}),
192
+ effective: getEffectiveConfig(localContent),
193
+ ...(show_secrets
194
+ ? {
195
+ warning: 'SECURITY WARNING: sensitive values are shown in plain text to the MCP client and may be included in the AI context.',
196
+ }
197
+ : {}),
104
198
  };
105
199
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
106
200
  });
@@ -25,11 +25,13 @@ function createMockServer() {
25
25
  return { registerTool, tools };
26
26
  }
27
27
  describe('registerEnvTools', () => {
28
- it('registers 3 env tools', () => {
28
+ it('registers environment inspection and mutation tools', () => {
29
29
  const server = createMockServer();
30
30
  registerEnvTools(server);
31
- expect(server.tools).toHaveLength(3);
31
+ expect(server.tools).toHaveLength(5);
32
32
  expect(server.tools.map((t) => t.name)).toEqual([
33
+ 'codapult_env_check',
34
+ 'codapult_env_sync',
33
35
  'codapult_env_schema',
34
36
  'codapult_env_read',
35
37
  'codapult_env_update',