@chapterdev/mcp-dev-studio 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/bin/mcp-dev-studio.js +2 -0
- package/dist/agent/fill.js +69 -0
- package/dist/agent/judge.js +24 -0
- package/dist/agent/loop-skill.js +103 -0
- package/dist/agent/providers.js +162 -0
- package/dist/agent/runner.js +252 -0
- package/dist/agent/starters.js +47 -0
- package/dist/analysis/estimate.js +7 -0
- package/dist/analysis/lint.js +149 -0
- package/dist/analysis/prefill.js +411 -0
- package/dist/analysis/surface.js +268 -0
- package/dist/analysis/tokens.js +69 -0
- package/dist/analytics/aggregate.js +106 -0
- package/dist/analytics/recorder.js +75 -0
- package/dist/analytics/tracker.js +58 -0
- package/dist/cli.js +264 -0
- package/dist/demo/seed.js +138 -0
- package/dist/demo/server.js +282 -0
- package/dist/demo/stdio.js +7 -0
- package/dist/discover.js +317 -0
- package/dist/eval/attempts.js +54 -0
- package/dist/eval/cli.js +183 -0
- package/dist/eval/journeys.js +161 -0
- package/dist/hosts/claude-code.js +403 -0
- package/dist/hosts/codex.js +328 -0
- package/dist/hosts/index.js +85 -0
- package/dist/hosts/models.js +51 -0
- package/dist/mcp/connection.js +330 -0
- package/dist/server/app.js +602 -0
- package/dist/server/listen.js +12 -0
- package/dist/skills/skills.js +203 -0
- package/dist/store-watch.js +75 -0
- package/dist/store.js +327 -0
- package/dist/types.js +3 -0
- package/dist/ui/assets/index-D9hmZSmq.js +55 -0
- package/dist/ui/assets/index-G_SSBQNV.css +2 -0
- package/dist/ui/index.html +17 -0
- package/dist/workspace.js +195 -0
- package/package.json +79 -4
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// A deliberately messy, realistic SaaS MCP server ("Ledgerly": CRM + billing).
|
|
2
|
+
// It is the --demo target, and it is designed to exercise every studio view:
|
|
3
|
+
//
|
|
4
|
+
// - overlapping tools: list_customers / find_customer / search_records,
|
|
5
|
+
// send_invoice / email_customer
|
|
6
|
+
// - one bloated payload: get_customer returns the whole raw record
|
|
7
|
+
// - one bloated schema: search_records ships a novel as its description
|
|
8
|
+
// - missing lifecycle: subscriptions can be created and listed, never
|
|
9
|
+
// cancelled or changed; customers can't be updated
|
|
10
|
+
// - discovery dead end: create_subscription needs a plan id that only a
|
|
11
|
+
// resource exposes, and it fails with "Error: failed"
|
|
12
|
+
// - missing param docs: create_customer, list_invoices
|
|
13
|
+
// - an MCP App: preview_invoice returns an HTML UI resource
|
|
14
|
+
//
|
|
15
|
+
// State is in memory and reseeded per process, so every eval run starts clean.
|
|
16
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
17
|
+
import { z } from 'zod';
|
|
18
|
+
const PLANS = [
|
|
19
|
+
{ id: 'plan_starter_m', name: 'Starter', interval: 'month', amount: 2900 },
|
|
20
|
+
{ id: 'plan_growth_m', name: 'Growth', interval: 'month', amount: 9900 },
|
|
21
|
+
{ id: 'plan_scale_y', name: 'Scale', interval: 'year', amount: 199000 },
|
|
22
|
+
];
|
|
23
|
+
function seed() {
|
|
24
|
+
const customers = [
|
|
25
|
+
['Ada Lovelace', 'ada@analytical.io', 'Analytical Engines', 'active'],
|
|
26
|
+
['Grace Hopper', 'grace@cobol.dev', 'Compiler Co', 'active'],
|
|
27
|
+
['Alan Turing', 'alan@bletchley.uk', 'Bletchley Labs', 'trial'],
|
|
28
|
+
['Katherine Johnson', 'kj@orbit.space', 'Orbit Mechanics', 'active'],
|
|
29
|
+
['Linus Torvalds', 'linus@kernel.org', 'Kernel Works', 'churned'],
|
|
30
|
+
['Margaret Hamilton', 'margaret@apollo.sh', 'Apollo Software', 'active'],
|
|
31
|
+
['Dennis Ritchie', 'dmr@bell.labs', 'Bell Labs', 'active'],
|
|
32
|
+
['Barbara Liskov', 'barbara@substitution.io', 'Substitution Inc', 'trial'],
|
|
33
|
+
].map(([name, email, company, status], i) => ({
|
|
34
|
+
id: `cus_${(1001 + i).toString(36)}${i}`,
|
|
35
|
+
name: name,
|
|
36
|
+
email: email,
|
|
37
|
+
company: company,
|
|
38
|
+
status: status,
|
|
39
|
+
createdAt: new Date(Date.UTC(2026, 0, 3 + i * 9)).toISOString(),
|
|
40
|
+
}));
|
|
41
|
+
const invoices = [
|
|
42
|
+
inv('inv_9001', customers[0].id, 'paid', [['Growth plan — Sep', 1, 9900]]),
|
|
43
|
+
inv('inv_9002', customers[1].id, 'sent', [['Onboarding workshop', 2, 45000]]),
|
|
44
|
+
inv('inv_9003', customers[3].id, 'draft', [['API overage', 12000, 2]]),
|
|
45
|
+
];
|
|
46
|
+
const subscriptions = [
|
|
47
|
+
{ id: 'sub_501', customer_id: customers[0].id, plan: 'plan_growth_m', status: 'active', started_at: '2026-02-01T00:00:00Z' },
|
|
48
|
+
{ id: 'sub_502', customer_id: customers[3].id, plan: 'plan_scale_y', status: 'active', started_at: '2026-03-12T00:00:00Z' },
|
|
49
|
+
{ id: 'sub_503', customer_id: customers[5].id, plan: 'plan_starter_m', status: 'past_due', started_at: '2026-05-20T00:00:00Z' },
|
|
50
|
+
];
|
|
51
|
+
return { customers, invoices, subscriptions };
|
|
52
|
+
}
|
|
53
|
+
function inv(id, customer_id, status, items) {
|
|
54
|
+
const line_items = items.map(([description, quantity, unit_amount]) => ({ description, quantity, unit_amount }));
|
|
55
|
+
return {
|
|
56
|
+
id,
|
|
57
|
+
customer_id,
|
|
58
|
+
status,
|
|
59
|
+
currency: 'usd',
|
|
60
|
+
line_items,
|
|
61
|
+
total: line_items.reduce((s, l) => s + l.quantity * l.unit_amount, 0),
|
|
62
|
+
due_date: '2026-12-15',
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const json = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value, null, 2) }] });
|
|
66
|
+
const fail = (text) => ({ isError: true, content: [{ type: 'text', text }] });
|
|
67
|
+
/** The raw "everything we have" record get_customer returns: the bloat. */
|
|
68
|
+
function rawCustomerRecord(c, db) {
|
|
69
|
+
const events = Array.from({ length: 60 }, (_, i) => ({
|
|
70
|
+
event_id: `evt_${c.id}_${i}`,
|
|
71
|
+
type: ['page_view', 'api_call', 'login', 'webhook_delivery', 'invoice_viewed'][i % 5],
|
|
72
|
+
occurred_at: new Date(Date.UTC(2026, 9, 1, i, i * 7 % 60)).toISOString(),
|
|
73
|
+
ip: `10.${i % 255}.${(i * 3) % 255}.${(i * 7) % 255}`,
|
|
74
|
+
user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
|
75
|
+
properties: { path: `/app/dashboard/${i}`, duration_ms: 120 + i * 13, experiment_bucket: i % 2 ? 'control' : 'variant_b', feature_flags: ['new_nav', 'beta_reports', 'ai_summaries'] },
|
|
76
|
+
}));
|
|
77
|
+
return {
|
|
78
|
+
...c,
|
|
79
|
+
object: 'customer',
|
|
80
|
+
livemode: true,
|
|
81
|
+
billing_profile: {
|
|
82
|
+
address: { line1: '1 Infinite Loop', line2: null, city: 'Cupertino', state: 'CA', postal_code: '95014', country: 'US' },
|
|
83
|
+
tax_ids: [{ type: 'us_ein', value: '12-3456789', verification: { status: 'verified', verified_at: '2026-01-04T00:00:00Z' } }],
|
|
84
|
+
payment_methods: [
|
|
85
|
+
{ id: 'pm_1', type: 'card', card: { brand: 'visa', last4: '4242', exp_month: 12, exp_year: 2029, checks: { cvc: 'pass', address: 'pass', postal: 'pass' }, fingerprint: 'Xt5EWLLDS7FJjR1c', networks: ['visa', 'cartes_bancaires'], three_d_secure_usage: { supported: true } } },
|
|
86
|
+
{ id: 'pm_2', type: 'us_bank_account', us_bank_account: { bank_name: 'STRIPE TEST BANK', last4: '6789', routing_number: '110000000', account_holder_type: 'company' } },
|
|
87
|
+
],
|
|
88
|
+
},
|
|
89
|
+
invoices: db.invoices.filter((i) => i.customer_id === c.id),
|
|
90
|
+
subscriptions: db.subscriptions.filter((s) => s.customer_id === c.id),
|
|
91
|
+
metadata: Object.fromEntries(Array.from({ length: 25 }, (_, i) => [`crm_field_${i}`, `legacy value ${i} imported from salesforce export batch 2025-11`])),
|
|
92
|
+
audit_log: events,
|
|
93
|
+
internal: { risk_score: 0.12, segment: 'mid-market', owner_id: 'usr_77', sync_state: { hubspot: 'ok', salesforce: 'stale', last_synced_at: '2026-11-01T00:00:00Z' } },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function invoiceHtml(i, c) {
|
|
97
|
+
const rows = i.line_items
|
|
98
|
+
.map((l) => `<tr><td>${l.description}</td><td>${l.quantity}</td><td>$${(l.unit_amount / 100).toFixed(2)}</td><td>$${((l.quantity * l.unit_amount) / 100).toFixed(2)}</td></tr>`)
|
|
99
|
+
.join('');
|
|
100
|
+
return `<!doctype html><html><head><meta charset="utf-8"><style>
|
|
101
|
+
body{font:13px/1.5 -apple-system,system-ui,sans-serif;margin:0;padding:20px;color:#1a1a1a;background:#fff}
|
|
102
|
+
.hd{display:flex;justify-content:space-between;align-items:baseline;border-bottom:1px solid #eee;padding-bottom:12px;margin-bottom:12px}
|
|
103
|
+
h1{font-size:16px;margin:0} .pill{font-size:11px;padding:2px 8px;border-radius:99px;background:#eef;color:#336;text-transform:uppercase;letter-spacing:.04em}
|
|
104
|
+
table{width:100%;border-collapse:collapse} td,th{text-align:left;padding:6px 4px;border-bottom:1px solid #f2f2f2} th{font-weight:500;color:#777;font-size:11px}
|
|
105
|
+
.tot{text-align:right;font-size:15px;font-weight:600;margin-top:12px} button{margin-top:12px;font:inherit;padding:6px 12px;border-radius:6px;border:1px solid #ccc;background:#fafafa;cursor:pointer}
|
|
106
|
+
</style></head><body>
|
|
107
|
+
<div class="hd"><h1>Invoice ${i.id}</h1><span class="pill">${i.status}</span></div>
|
|
108
|
+
<div>Bill to <b>${c?.name ?? i.customer_id}</b> · ${c?.company ?? ''} · due ${i.due_date}</div>
|
|
109
|
+
<table><thead><tr><th>Item</th><th>Qty</th><th>Unit</th><th>Amount</th></tr></thead><tbody>${rows}</tbody></table>
|
|
110
|
+
<div class="tot">Total $${(i.total / 100).toFixed(2)} ${i.currency.toUpperCase()}</div>
|
|
111
|
+
<button onclick="this.textContent='Copied link ✓'">Copy payment link</button>
|
|
112
|
+
</body></html>`;
|
|
113
|
+
}
|
|
114
|
+
const SEARCH_RECORDS_DESCRIPTION = `Search across all records in the Ledgerly workspace. This is the universal search endpoint and it can be used to search for customers, invoices, subscriptions, payments, refunds, credit notes, products, prices, coupons, tax rates, events, webhooks, and anything else stored in Ledgerly.
|
|
115
|
+
|
|
116
|
+
The query language supports the following operators and syntax. Field filters use the form field:value, for example email:ada@analytical.io or status:active. Multiple filters are combined with AND by default; use OR between terms to combine with OR. Use a leading minus to negate a filter, for example -status:churned. Ranges are supported for numeric and date fields with the syntax field:[start TO end], for example created:[2026-01-01 TO 2026-06-30] or total:[1000 TO 50000]. Wildcards are supported with * at the end of a term, for example name:Ada*. Phrases can be quoted, for example company:"Analytical Engines". Nested fields can be addressed with dot notation, for example billing_profile.address.country:US. Metadata fields can be searched with metadata.key:value. The search is case insensitive for text fields and exact for identifiers. Results are ranked by relevance using BM25 with a recency boost unless sort is specified. Sorting supports any indexed field with asc or desc. Pagination uses opaque cursors; pass the next_cursor value from a previous response to get the next page. The maximum page size is 100 and the default is 20.
|
|
117
|
+
|
|
118
|
+
Indexed fields for customers: id, name, email, company, status, created, metadata.*, billing_profile.address.*. Indexed fields for invoices: id, customer_id, status, currency, total, due_date, created, sent_at, metadata.*. Indexed fields for subscriptions: id, customer_id, plan, status, started_at, current_period_end, metadata.*. Indexed fields for payments: id, invoice_id, amount, status, method, created. Indexed fields for refunds: id, payment_id, amount, reason, created. Indexed fields for credit notes: id, invoice_id, amount, reason, created. Indexed fields for products: id, name, active, created. Indexed fields for prices: id, product_id, unit_amount, currency, interval, active. Indexed fields for coupons: id, percent_off, amount_off, duration, valid. Indexed fields for events: id, type, created. Indexed fields for webhooks: id, url, status, created.
|
|
119
|
+
|
|
120
|
+
Rate limits: the search endpoint is limited to 20 requests per second per workspace. Search indexes are eventually consistent and typically reflect writes within 1 to 3 seconds, but during heavy load this may take up to 60 seconds. If you need strongly consistent reads, use the get endpoints for the specific record type instead of search. Deleted records are excluded from search results unless include_deleted:true is passed in the query. Archived records are included by default. Test mode and live mode records are searched separately depending on the API key used. Note that search results contain a summary of each record, not the full record; to get the full record call the relevant get tool. This tool should be used whenever the user wants to find anything.`;
|
|
121
|
+
export function createDemoServer() {
|
|
122
|
+
const db = seed();
|
|
123
|
+
const server = new McpServer({ name: 'ledgerly', version: '0.9.3' }, { instructions: 'Ledgerly: customers, invoices and subscriptions for B2B SaaS billing.' });
|
|
124
|
+
server.registerTool('list_customers', {
|
|
125
|
+
description: 'List customers in the workspace. Supports filtering by status and pagination.',
|
|
126
|
+
inputSchema: {
|
|
127
|
+
status: z.enum(['active', 'churned', 'trial']).optional().describe('Only return customers with this status'),
|
|
128
|
+
limit: z.number().int().min(1).max(100).optional().describe('Max results (default 20)'),
|
|
129
|
+
},
|
|
130
|
+
annotations: { readOnlyHint: true },
|
|
131
|
+
}, async ({ status, limit }) => json(db.customers.filter((c) => !status || c.status === status).slice(0, limit ?? 20).map(({ id, name, email, company, status }) => ({ id, name, email, company, status }))));
|
|
132
|
+
server.registerTool('find_customer', {
|
|
133
|
+
description: 'Search for customers by name or email address. Returns matching customers.',
|
|
134
|
+
inputSchema: { query: z.string().describe('Name or email to search for') },
|
|
135
|
+
annotations: { readOnlyHint: true },
|
|
136
|
+
}, async ({ query }) => {
|
|
137
|
+
const q = query.toLowerCase();
|
|
138
|
+
return json(db.customers.filter((c) => c.name.toLowerCase().includes(q) || c.email.toLowerCase().includes(q)).map(({ id, name, email, status }) => ({ id, name, email, status })));
|
|
139
|
+
});
|
|
140
|
+
server.registerTool('get_customer', {
|
|
141
|
+
description: 'Get a customer by ID. Returns the complete customer record.',
|
|
142
|
+
inputSchema: { customer_id: z.string().describe('Customer ID, e.g. cus_xxx') },
|
|
143
|
+
annotations: { readOnlyHint: true },
|
|
144
|
+
}, async ({ customer_id }) => {
|
|
145
|
+
const c = db.customers.find((x) => x.id === customer_id);
|
|
146
|
+
return c ? json(rawCustomerRecord(c, db)) : fail(`No customer with id ${customer_id}. Use find_customer or list_customers to look up ids.`);
|
|
147
|
+
});
|
|
148
|
+
server.registerTool('create_customer', {
|
|
149
|
+
description: 'Create a new customer.',
|
|
150
|
+
inputSchema: {
|
|
151
|
+
name: z.string(),
|
|
152
|
+
email: z.string(),
|
|
153
|
+
company: z.string().optional(),
|
|
154
|
+
},
|
|
155
|
+
}, async ({ name, email, company }) => {
|
|
156
|
+
if (db.customers.some((c) => c.email === email))
|
|
157
|
+
return fail('Error: customer already exists');
|
|
158
|
+
const c = { id: `cus_${Math.random().toString(36).slice(2, 8)}`, name, email, company: company ?? '', status: 'trial', createdAt: new Date().toISOString() };
|
|
159
|
+
db.customers.push(c);
|
|
160
|
+
return json(c);
|
|
161
|
+
});
|
|
162
|
+
server.registerTool('create_invoice', {
|
|
163
|
+
description: 'Create a draft invoice for a customer. Amounts are in cents. The invoice is not sent until send_invoice is called. Returns the invoice with its id. Fails if the customer does not exist.',
|
|
164
|
+
inputSchema: {
|
|
165
|
+
customer_id: z.string().describe('Customer to bill'),
|
|
166
|
+
line_items: z
|
|
167
|
+
.array(z.object({
|
|
168
|
+
description: z.string().describe('What is being billed'),
|
|
169
|
+
quantity: z.number().int().min(1).describe('Units'),
|
|
170
|
+
unit_amount: z.number().int().min(0).describe('Price per unit in cents'),
|
|
171
|
+
}))
|
|
172
|
+
.min(1)
|
|
173
|
+
.describe('Line items on the invoice'),
|
|
174
|
+
currency: z.string().optional().describe('ISO currency code (default usd)'),
|
|
175
|
+
due_days: z.number().int().optional().describe('Days until due (default 30)'),
|
|
176
|
+
},
|
|
177
|
+
}, async ({ customer_id, line_items, currency, due_days }) => {
|
|
178
|
+
if (!db.customers.some((c) => c.id === customer_id))
|
|
179
|
+
return fail(`Customer ${customer_id} not found. Look it up with find_customer first.`);
|
|
180
|
+
const due = new Date(Date.now() + (due_days ?? 30) * 86400_000).toISOString().slice(0, 10);
|
|
181
|
+
const i = { ...inv(`inv_${9000 + db.invoices.length + 1}`, customer_id, 'draft', line_items.map((l) => [l.description, l.quantity, l.unit_amount])), currency: currency ?? 'usd', due_date: due };
|
|
182
|
+
db.invoices.push(i);
|
|
183
|
+
return json(i);
|
|
184
|
+
});
|
|
185
|
+
server.registerTool('list_invoices', {
|
|
186
|
+
description: 'List invoices.',
|
|
187
|
+
inputSchema: {
|
|
188
|
+
customer_id: z.string().optional(),
|
|
189
|
+
status: z.enum(['draft', 'sent', 'paid', 'void']).optional(),
|
|
190
|
+
},
|
|
191
|
+
annotations: { readOnlyHint: true },
|
|
192
|
+
}, async ({ customer_id, status }) => json(db.invoices.filter((i) => (!customer_id || i.customer_id === customer_id) && (!status || i.status === status))));
|
|
193
|
+
server.registerTool('send_invoice', {
|
|
194
|
+
description: 'Send an invoice to the customer by email. Moves a draft invoice to sent.',
|
|
195
|
+
inputSchema: { invoice_id: z.string().describe('Invoice to send') },
|
|
196
|
+
}, async ({ invoice_id }) => {
|
|
197
|
+
const i = db.invoices.find((x) => x.id === invoice_id);
|
|
198
|
+
if (!i)
|
|
199
|
+
return fail(`Invoice ${invoice_id} not found.`);
|
|
200
|
+
if (i.status !== 'draft')
|
|
201
|
+
return fail(`Invoice ${invoice_id} is ${i.status}; only draft invoices can be sent.`);
|
|
202
|
+
i.status = 'sent';
|
|
203
|
+
i.sent_at = new Date().toISOString();
|
|
204
|
+
return json({ ok: true, invoice_id, status: i.status, sent_to: db.customers.find((c) => c.id === i.customer_id)?.email });
|
|
205
|
+
});
|
|
206
|
+
server.registerTool('preview_invoice', {
|
|
207
|
+
description: 'Render an invoice as a visual preview the user can see. Use after creating an invoice so the user can review it before sending.',
|
|
208
|
+
inputSchema: { invoice_id: z.string().describe('Invoice to preview') },
|
|
209
|
+
annotations: { readOnlyHint: true },
|
|
210
|
+
_meta: { ui: { resourceUri: 'ui://ledgerly/invoice-preview' } },
|
|
211
|
+
}, async ({ invoice_id }) => {
|
|
212
|
+
const i = db.invoices.find((x) => x.id === invoice_id);
|
|
213
|
+
if (!i)
|
|
214
|
+
return fail(`Invoice ${invoice_id} not found.`);
|
|
215
|
+
const c = db.customers.find((x) => x.id === i.customer_id);
|
|
216
|
+
return {
|
|
217
|
+
content: [
|
|
218
|
+
{ type: 'text', text: `Rendered preview of ${i.id} (${i.status}, total ${(i.total / 100).toFixed(2)} ${i.currency}).` },
|
|
219
|
+
{ type: 'resource', resource: { uri: `ui://ledgerly/invoice-preview/${i.id}`, mimeType: 'text/html;profile=mcp-app', text: invoiceHtml(i, c) } },
|
|
220
|
+
],
|
|
221
|
+
};
|
|
222
|
+
});
|
|
223
|
+
server.registerTool('email_customer', {
|
|
224
|
+
description: 'Send an email to a customer. Can be used to send invoices, reminders, or any message.',
|
|
225
|
+
inputSchema: {
|
|
226
|
+
customer_id: z.string().describe('Recipient customer'),
|
|
227
|
+
subject: z.string().describe('Subject line'),
|
|
228
|
+
body: z.string().describe('Plain text body'),
|
|
229
|
+
},
|
|
230
|
+
}, async ({ customer_id, subject }) => {
|
|
231
|
+
const c = db.customers.find((x) => x.id === customer_id);
|
|
232
|
+
if (!c)
|
|
233
|
+
return fail('Error');
|
|
234
|
+
return json({ ok: true, to: c.email, subject });
|
|
235
|
+
});
|
|
236
|
+
server.registerTool('create_subscription', {
|
|
237
|
+
description: 'Subscribe a customer to a plan.',
|
|
238
|
+
inputSchema: {
|
|
239
|
+
customer_id: z.string().describe('Customer to subscribe'),
|
|
240
|
+
plan: z.string().describe('Plan ID'),
|
|
241
|
+
},
|
|
242
|
+
}, async ({ customer_id, plan }) => {
|
|
243
|
+
if (!db.customers.some((c) => c.id === customer_id) || !PLANS.some((p) => p.id === plan))
|
|
244
|
+
return fail('Error: failed');
|
|
245
|
+
const s = { id: `sub_${500 + db.subscriptions.length + 1}`, customer_id, plan, status: 'active', started_at: new Date().toISOString() };
|
|
246
|
+
db.subscriptions.push(s);
|
|
247
|
+
return json(s);
|
|
248
|
+
});
|
|
249
|
+
server.registerTool('list_subscriptions', {
|
|
250
|
+
description: 'List subscriptions, optionally for one customer.',
|
|
251
|
+
inputSchema: {
|
|
252
|
+
customer_id: z.string().optional().describe('Only this customer'),
|
|
253
|
+
status: z.enum(['active', 'past_due', 'cancelled']).optional().describe('Filter by status'),
|
|
254
|
+
},
|
|
255
|
+
annotations: { readOnlyHint: true },
|
|
256
|
+
}, async ({ customer_id, status }) => json(db.subscriptions.filter((s) => (!customer_id || s.customer_id === customer_id) && (!status || s.status === status))));
|
|
257
|
+
server.registerTool('search_records', {
|
|
258
|
+
description: SEARCH_RECORDS_DESCRIPTION,
|
|
259
|
+
inputSchema: {
|
|
260
|
+
query: z.string().describe('Search query using the Ledgerly query language described above'),
|
|
261
|
+
types: z.array(z.string()).optional().describe('Record types to include'),
|
|
262
|
+
sort: z.string().optional().describe('Field and direction, e.g. created:desc'),
|
|
263
|
+
limit: z.number().int().optional().describe('Page size, max 100'),
|
|
264
|
+
cursor: z.string().optional().describe('Pagination cursor'),
|
|
265
|
+
},
|
|
266
|
+
annotations: { readOnlyHint: true },
|
|
267
|
+
}, async ({ query }) => {
|
|
268
|
+
const q = query.toLowerCase().replace(/\w+:/g, '').replace(/"/g, '').trim();
|
|
269
|
+
const hits = [
|
|
270
|
+
...db.customers.filter((c) => JSON.stringify(c).toLowerCase().includes(q)).map((c) => ({ type: 'customer', id: c.id, summary: `${c.name} <${c.email}>` })),
|
|
271
|
+
...db.invoices.filter((i) => JSON.stringify(i).toLowerCase().includes(q)).map((i) => ({ type: 'invoice', id: i.id, summary: `${i.status} ${(i.total / 100).toFixed(2)}` })),
|
|
272
|
+
];
|
|
273
|
+
return json({ results: hits, next_cursor: null });
|
|
274
|
+
});
|
|
275
|
+
server.registerResource('plans', 'ledgerly://plans', { description: 'Plan catalog with plan IDs and prices', mimeType: 'application/json' }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify(PLANS, null, 2) }] }));
|
|
276
|
+
server.registerResource('invoice-preview', 'ui://ledgerly/invoice-preview', { description: 'MCP App template for invoice previews', mimeType: 'text/html;profile=mcp-app' }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/html;profile=mcp-app', text: invoiceHtml(db.invoices[0], db.customers[0]) }] }));
|
|
277
|
+
server.registerPrompt('month_end_close', { description: 'Walk through invoicing every active customer for the month', argsSchema: { month: z.string().describe('Month, e.g. 2026-11') } }, ({ month }) => ({
|
|
278
|
+
messages: [{ role: 'user', content: { type: 'text', text: `Close out ${month}: make sure every active customer has a sent invoice for this month.` } }],
|
|
279
|
+
}));
|
|
280
|
+
return server;
|
|
281
|
+
}
|
|
282
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Entry point for the demo server over stdio: `node dist/demo/stdio.js`.
|
|
2
|
+
// --demo spawns this as a real child process, so the demo goes through the
|
|
3
|
+
// exact same transport, reconnect and hot-refresh paths as a user's server.
|
|
4
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
5
|
+
import { createDemoServer } from './server.js';
|
|
6
|
+
await createDemoServer().connect(new StdioServerTransport());
|
|
7
|
+
//# sourceMappingURL=stdio.js.map
|
package/dist/discover.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// Find the MCP server(s) a project already has, so `npx @chapterdev/mcp-dev-studio` can
|
|
2
|
+
// start without flags.
|
|
3
|
+
//
|
|
4
|
+
// Sources, most trusted first:
|
|
5
|
+
// - .mcp.json, .cursor/mcp.json, .vscode/mcp.json (servers the project declares)
|
|
6
|
+
// - Claude Code's local-scope servers for this folder (~/.claude.json)
|
|
7
|
+
// - package.json / pyproject.toml of the project and its workspaces: a package
|
|
8
|
+
// that depends on an MCP SDK, with its transport read from the source
|
|
9
|
+
//
|
|
10
|
+
// Nothing here starts a process or contacts a remote host. Only localhost URLs
|
|
11
|
+
// are probed (one initialize POST, to see whether the server is up and wants a token).
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { basename, dirname, join, relative, resolve } from 'node:path';
|
|
16
|
+
const SDK_DEPS = ['@modelcontextprotocol/sdk', '@modelcontextprotocol/server', 'fastmcp', 'mcp-framework', 'mcp-use', 'xmcp', '@vercel/mcp-adapter', 'mcp-handler'];
|
|
17
|
+
const PY_DEPS = /["'\s](mcp|fastmcp)(\[[^\]]*\])?\s*([<>=~!]|["',\]])/;
|
|
18
|
+
export const isLocalUrl = (u) => {
|
|
19
|
+
try {
|
|
20
|
+
return /^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|.*\.localhost|.*\.test)$/.test(new URL(u).hostname);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const idOf = (t) => createHash('sha1').update(t.kind === 'stdio' ? `${t.cwd ?? ''}|${t.command}` : t.url).digest('hex').slice(0, 10);
|
|
27
|
+
/** Expand ${VAR} and ${VAR:-default}, as Claude Code does in .mcp.json. */
|
|
28
|
+
function expand(s, env = process.env) {
|
|
29
|
+
return s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_m, k, d) => env[k] ?? d ?? '');
|
|
30
|
+
}
|
|
31
|
+
const quote = (a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `"${a.replace(/"/g, '\\"')}"`);
|
|
32
|
+
function readJson(file) {
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function fromEntry(name, e, from, cwd) {
|
|
41
|
+
let target;
|
|
42
|
+
if (e.url || e.type === 'http' || e.type === 'sse' || e.type === 'streamable-http') {
|
|
43
|
+
if (!e.url)
|
|
44
|
+
return undefined;
|
|
45
|
+
const headers = e.headers ? Object.fromEntries(Object.entries(e.headers).map(([k, v]) => [k, expand(String(v))])) : undefined;
|
|
46
|
+
target = { kind: 'http', url: expand(e.url), ...(headers && Object.keys(headers).length ? { headers } : {}) };
|
|
47
|
+
}
|
|
48
|
+
else if (e.command) {
|
|
49
|
+
const env = e.env ? Object.fromEntries(Object.entries(e.env).map(([k, v]) => [k, expand(String(v))])) : undefined;
|
|
50
|
+
target = { kind: 'stdio', command: [e.command, ...(e.args ?? [])].map((a) => quote(expand(String(a)))).join(' '), cwd: e.cwd ? resolve(cwd, expand(e.cwd)) : cwd, ...(env ? { env } : {}) };
|
|
51
|
+
}
|
|
52
|
+
else
|
|
53
|
+
return undefined;
|
|
54
|
+
return { id: idOf(target), name, from, target, local: target.kind === 'stdio' || isLocalUrl(target.url), declared: true };
|
|
55
|
+
}
|
|
56
|
+
function configServers(root) {
|
|
57
|
+
const out = [];
|
|
58
|
+
for (const [file, key] of [['.mcp.json', 'mcpServers'], ['.cursor/mcp.json', 'mcpServers'], ['.vscode/mcp.json', 'servers']]) {
|
|
59
|
+
const json = readJson(join(root, file));
|
|
60
|
+
for (const [name, e] of Object.entries(json?.[key] ?? json?.mcpServers ?? {})) {
|
|
61
|
+
const c = fromEntry(name, e, file, root);
|
|
62
|
+
if (c)
|
|
63
|
+
out.push(c);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
/** Claude Code's "local" scope: servers added with `claude mcp add` inside this folder (or a parent). */
|
|
69
|
+
function claudeLocalServers(root) {
|
|
70
|
+
const cfg = readJson(join(homedir(), '.claude.json'));
|
|
71
|
+
if (!cfg?.projects)
|
|
72
|
+
return [];
|
|
73
|
+
for (let dir = root;; dir = dirname(dir)) {
|
|
74
|
+
const servers = cfg.projects[dir]?.mcpServers;
|
|
75
|
+
if (servers && Object.keys(servers).length) {
|
|
76
|
+
return Object.entries(servers)
|
|
77
|
+
.map(([name, e]) => fromEntry(name, e, 'Claude Code', dir))
|
|
78
|
+
.filter((c) => !!c);
|
|
79
|
+
}
|
|
80
|
+
if (dirname(dir) === dir)
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function packageManager(root) {
|
|
85
|
+
for (let dir = root;; dir = dirname(dir)) {
|
|
86
|
+
if (existsSync(join(dir, 'pnpm-lock.yaml')))
|
|
87
|
+
return 'pnpm';
|
|
88
|
+
if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock')))
|
|
89
|
+
return 'bun';
|
|
90
|
+
if (existsSync(join(dir, 'yarn.lock')))
|
|
91
|
+
return 'yarn';
|
|
92
|
+
if (existsSync(join(dir, 'package-lock.json')))
|
|
93
|
+
return 'npm';
|
|
94
|
+
if (dirname(dir) === dir)
|
|
95
|
+
return 'npm';
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Workspace package folders: package.json "workspaces" or pnpm-workspace.yaml, `dir/*` globs only. */
|
|
99
|
+
function workspaceDirs(root, pkg) {
|
|
100
|
+
const globs = [];
|
|
101
|
+
const ws = pkg?.workspaces;
|
|
102
|
+
globs.push(...(Array.isArray(ws) ? ws : ws?.packages ?? []));
|
|
103
|
+
try {
|
|
104
|
+
const yaml = readFileSync(join(root, 'pnpm-workspace.yaml'), 'utf8');
|
|
105
|
+
for (const m of yaml.matchAll(/^\s*-\s*['"]?([^'"\n#]+?)['"]?\s*$/gm))
|
|
106
|
+
globs.push(m[1]);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
/* not pnpm */
|
|
110
|
+
}
|
|
111
|
+
const dirs = [];
|
|
112
|
+
for (const g of globs) {
|
|
113
|
+
if (g.startsWith('!'))
|
|
114
|
+
continue;
|
|
115
|
+
if (g.endsWith('/*') || g.endsWith('/**')) {
|
|
116
|
+
const base = join(root, g.replace(/\/\*\*?$/, ''));
|
|
117
|
+
try {
|
|
118
|
+
for (const d of readdirSync(base))
|
|
119
|
+
if (existsSync(join(base, d, 'package.json')) || existsSync(join(base, d, 'pyproject.toml')))
|
|
120
|
+
dirs.push(join(base, d));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
/* missing folder */
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
else if (existsSync(join(root, g)))
|
|
127
|
+
dirs.push(join(root, g));
|
|
128
|
+
}
|
|
129
|
+
return dirs;
|
|
130
|
+
}
|
|
131
|
+
/** Source files worth reading to learn the transport, port and path (bounded). */
|
|
132
|
+
function sourceFiles(dir, limit = 400) {
|
|
133
|
+
const out = [];
|
|
134
|
+
const walk = (d, depth) => {
|
|
135
|
+
if (out.length >= limit || depth > 5)
|
|
136
|
+
return;
|
|
137
|
+
let entries;
|
|
138
|
+
try {
|
|
139
|
+
entries = readdirSync(d);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
for (const e of entries) {
|
|
145
|
+
if (/^(node_modules|dist|build|\.next|\.git|\.repos|coverage|out|\.venv|venv|__pycache__|\.mcp-dev-studio)$/.test(e) || e.startsWith('.'))
|
|
146
|
+
continue;
|
|
147
|
+
const p = join(d, e);
|
|
148
|
+
let st;
|
|
149
|
+
try {
|
|
150
|
+
st = statSync(p);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (st.isDirectory())
|
|
156
|
+
walk(p, depth + 1);
|
|
157
|
+
else if (/\.(m?[jt]sx?|cjs|py)$/.test(e) && !/\.(test|spec|d)\./.test(e) && st.size < 400_000)
|
|
158
|
+
out.push(p);
|
|
159
|
+
if (out.length >= limit)
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
walk(dir, 0);
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
const JS_STDIO = /\bStdioServerTransport\b|transportType\s*:\s*["']stdio["']/;
|
|
167
|
+
const JS_HTTP = /\b(StreamableHTTPServerTransport|SSEServerTransport|createMcpHandler)\b|transportType\s*:\s*["'](httpStream|sse)["']/;
|
|
168
|
+
const PY_STDIO = /\bstdio_server\b|\.run\(\s*\)|\.run\(\s*transport\s*=\s*["']stdio["']/;
|
|
169
|
+
const PY_HTTP = /\.run\(\s*transport\s*=\s*["'](streamable-http|http|sse)["']|streamable_http_app|sse_app/;
|
|
170
|
+
/** PORT=… from the package's or project's .env files (dev scripts usually load them). */
|
|
171
|
+
function envPort(dirs) {
|
|
172
|
+
for (const d of dirs) {
|
|
173
|
+
for (const f of ['.env', '.env.local', '.env.development', '.env.example']) {
|
|
174
|
+
try {
|
|
175
|
+
const m = /^\s*PORT\s*=\s*["']?(\d{2,5})/m.exec(readFileSync(join(d, f), 'utf8'));
|
|
176
|
+
if (m)
|
|
177
|
+
return Number(m[1]);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
/* no file */
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
function scanSource(dir, root) {
|
|
187
|
+
const scan = { stdio: false, http: false };
|
|
188
|
+
const ports = [];
|
|
189
|
+
for (const f of sourceFiles(dir)) {
|
|
190
|
+
const src = readFileSync(f, 'utf8');
|
|
191
|
+
const py = f.endsWith('.py');
|
|
192
|
+
const stdio = (py ? PY_STDIO : JS_STDIO).test(src);
|
|
193
|
+
const http = (py ? PY_HTTP : JS_HTTP).test(src);
|
|
194
|
+
scan.stdio ||= stdio;
|
|
195
|
+
scan.http ||= http;
|
|
196
|
+
// A default port: `PORT ?? 3001`, `PORT ? Number(PORT) : 3001`, `.listen(3001`, `port: 3001`, `port=3001`.
|
|
197
|
+
for (const m of src.matchAll(/(?:PORT\b[^\n;]{0,40}?(?:\?\?|\|\||:|\bor\b)\s*|\.listen\(\s*|\bport\s*[:=]\s*)["']?(\d{4,5})(?![\d_])/g)) {
|
|
198
|
+
const port = Number(m[1]);
|
|
199
|
+
if (port < 1024 || port > 65535)
|
|
200
|
+
continue;
|
|
201
|
+
const score = (/PORT/.test(m[0]) ? 3 : 0) + (/\.listen/.test(m[0]) ? 2 : 0) + (http ? 2 : 0) + (/(^|\/)(index|server|main|app)\.\w+$/.test(f) ? 1 : 0);
|
|
202
|
+
ports.push({ port, score });
|
|
203
|
+
}
|
|
204
|
+
if (!scan.path && http)
|
|
205
|
+
scan.path = /["'`](\/(?:api\/)?mcp)["'`]/.exec(src)?.[1];
|
|
206
|
+
}
|
|
207
|
+
if (!scan.path)
|
|
208
|
+
for (const f of sourceFiles(dir, 80))
|
|
209
|
+
if ((scan.path = /["'`](\/(?:api\/)?mcp)["'`]/.exec(readFileSync(f, 'utf8'))?.[1]))
|
|
210
|
+
break;
|
|
211
|
+
scan.port = envPort([dir, root]) ?? ports.sort((a, b) => b.score - a.score)[0]?.port;
|
|
212
|
+
return scan;
|
|
213
|
+
}
|
|
214
|
+
function scriptFor(pkg, prefer) {
|
|
215
|
+
return prefer.find((s) => pkg.scripts?.[s]);
|
|
216
|
+
}
|
|
217
|
+
function nodePackage(dir, root) {
|
|
218
|
+
const pkg = readJson(join(dir, 'package.json'));
|
|
219
|
+
if (!pkg)
|
|
220
|
+
return [];
|
|
221
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
222
|
+
if (!SDK_DEPS.some((d) => d in deps))
|
|
223
|
+
return [];
|
|
224
|
+
const scan = scanSource(dir, root);
|
|
225
|
+
if (!scan.stdio && !scan.http)
|
|
226
|
+
return [];
|
|
227
|
+
const pm = packageManager(dir);
|
|
228
|
+
const run = (script) => (pm === 'npm' ? `npm run -s ${script}` : pm === 'yarn' ? `yarn -s ${script}` : `${pm} run -s ${script}`);
|
|
229
|
+
const name = pkg.name || basename(dir);
|
|
230
|
+
const from = relative(root, dir) || 'package.json';
|
|
231
|
+
const out = [];
|
|
232
|
+
if (scan.stdio) {
|
|
233
|
+
const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin ? Object.values(pkg.bin)[0] : undefined;
|
|
234
|
+
const script = scriptFor(pkg, ['mcp', 'stdio', 'start:stdio', 'start', 'dev']);
|
|
235
|
+
const command = bin && existsSync(join(dir, bin)) ? `node ${quote(bin)}` : script ? run(script) : undefined;
|
|
236
|
+
if (command) {
|
|
237
|
+
const target = { kind: 'stdio', command, cwd: dir };
|
|
238
|
+
out.push({ id: idOf(target), name, from, target, local: true, declared: false });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (scan.http) {
|
|
242
|
+
const url = `http://localhost:${scan.port ?? 3000}${scan.path ?? '/mcp'}`;
|
|
243
|
+
const target = { kind: 'http', url };
|
|
244
|
+
const script = scriptFor(pkg, ['dev', 'start', 'serve']);
|
|
245
|
+
out.push({ id: idOf(target), name, from, target, local: true, declared: false, ...(script ? { start: { command: run(script), cwd: dir } } : {}) });
|
|
246
|
+
}
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
function pythonPackage(dir, root) {
|
|
250
|
+
let toml;
|
|
251
|
+
try {
|
|
252
|
+
toml = readFileSync(join(dir, 'pyproject.toml'), 'utf8');
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
return [];
|
|
256
|
+
}
|
|
257
|
+
if (!PY_DEPS.test(toml))
|
|
258
|
+
return [];
|
|
259
|
+
const scan = scanSource(dir, root);
|
|
260
|
+
if (!scan.stdio && !scan.http)
|
|
261
|
+
return [];
|
|
262
|
+
const uv = existsSync(join(dir, 'uv.lock')) || existsSync(join(root, 'uv.lock'));
|
|
263
|
+
const script = /\[project\.scripts\]\s*\n\s*([\w-]+)\s*=/.exec(toml)?.[1];
|
|
264
|
+
const name = /^name\s*=\s*["']([^"']+)/m.exec(toml)?.[1] ?? basename(dir);
|
|
265
|
+
if (!script || !scan.stdio)
|
|
266
|
+
return [];
|
|
267
|
+
const target = { kind: 'stdio', command: uv ? `uv run ${script}` : script, cwd: dir };
|
|
268
|
+
return [{ id: idOf(target), name, from: relative(root, dir) || 'pyproject.toml', target, local: true, declared: false }];
|
|
269
|
+
}
|
|
270
|
+
function packageServers(root) {
|
|
271
|
+
const pkg = readJson(join(root, 'package.json'));
|
|
272
|
+
const dirs = [root, ...workspaceDirs(root, pkg)];
|
|
273
|
+
return dirs.flatMap((d) => [...nodePackage(d, root), ...pythonPackage(d, root)]);
|
|
274
|
+
}
|
|
275
|
+
// ── probing ──
|
|
276
|
+
/** POST an initialize to a local URL: is anything there, and does it want a token? */
|
|
277
|
+
export async function probe(url, headers, timeoutMs = 1500) {
|
|
278
|
+
try {
|
|
279
|
+
const res = await fetch(url, {
|
|
280
|
+
method: 'POST',
|
|
281
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...headers },
|
|
282
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 0, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'mcp-dev-studio-probe', version: '0' } } }),
|
|
283
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
284
|
+
});
|
|
285
|
+
void res.body?.cancel().catch(() => { });
|
|
286
|
+
return { running: true, needsToken: res.status === 401 || res.status === 403 };
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
return { running: false, needsToken: false };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/** Everything that looks like an MCP server for this folder, best first. */
|
|
293
|
+
export async function discover(root) {
|
|
294
|
+
const seen = new Map();
|
|
295
|
+
for (const c of [...configServers(root), ...claudeLocalServers(root), ...packageServers(root)]) {
|
|
296
|
+
// The same server can be declared and detected; keep the declared one, but learn how to start it.
|
|
297
|
+
const prev = seen.get(c.id);
|
|
298
|
+
if (prev)
|
|
299
|
+
prev.start ??= c.start;
|
|
300
|
+
else
|
|
301
|
+
seen.set(c.id, c);
|
|
302
|
+
}
|
|
303
|
+
const list = [...seen.values()];
|
|
304
|
+
await Promise.all(list.filter((c) => c.target.kind === 'http' && c.local).map(async (c) => Object.assign(c, await probe(c.target.url, c.target.headers))));
|
|
305
|
+
const score = (c) => (c.local ? 0 : 100) + (c.declared ? 0 : 10) + (c.target.kind === 'http' && !c.running ? 5 : 0);
|
|
306
|
+
return list.sort((a, b) => score(a) - score(b));
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* The one candidate safe to connect to without asking, if there is exactly one:
|
|
310
|
+
* a declared stdio server, or a local HTTP server that's up and needs no token.
|
|
311
|
+
* Guessed commands are never run without a click.
|
|
312
|
+
*/
|
|
313
|
+
export function autoPick(list) {
|
|
314
|
+
const ok = list.filter((c) => c.local && (c.target.kind === 'stdio' ? c.declared : c.running && !c.needsToken));
|
|
315
|
+
return ok.length === 1 ? ok[0] : undefined;
|
|
316
|
+
}
|
|
317
|
+
//# sourceMappingURL=discover.js.map
|