@qmingjun/dsh-eda-mcp 0.0.0-stage → 1.1.12

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 (53) hide show
  1. package/AGENTS.md +63 -0
  2. package/CHANGELOG.md +792 -0
  3. package/CONTRIBUTING.md +154 -0
  4. package/LICENSE +55 -0
  5. package/README.md +290 -2
  6. package/README.zh.md +449 -0
  7. package/cordis.patch.yml +7 -0
  8. package/docs/design-rules.md +254 -0
  9. package/docs/dsh-version-sweep.md +73 -0
  10. package/docs/pitfalls.md +99 -0
  11. package/docs/project-status.md +100 -0
  12. package/docs/release.md +215 -0
  13. package/docs/schematic-workflow.md +297 -0
  14. package/docs/tools.md +184 -0
  15. package/jlc-extension/api-bridge.js +879 -0
  16. package/jlc-extension/extension.json +104 -0
  17. package/lib/bridge.mjs +4179 -0
  18. package/lib/client.js +1605 -0
  19. package/lib/extension-digest.json +6 -0
  20. package/lib/index.js +1261 -0
  21. package/package.json +144 -4
  22. package/src/bridge/design-intake.ts +133 -0
  23. package/src/bridge/design-rules.ts +228 -0
  24. package/src/bridge/eda-launch.ts +267 -0
  25. package/src/bridge/extension-package.ts +35 -0
  26. package/src/bridge/index.ts +3576 -0
  27. package/src/bridge/netlist-erc.ts +305 -0
  28. package/src/bridge/schematic-audit.ts +131 -0
  29. package/src/bridge/workflow-guide.ts +65 -0
  30. package/src/bridge-diagnostics.ts +185 -0
  31. package/src/client/EdaMcpSettingsCard.tsx +571 -0
  32. package/src/client/index.ts +40 -0
  33. package/src/client/locales.ts +83 -0
  34. package/src/client/settings-scope.ts +160 -0
  35. package/src/config-values.ts +60 -0
  36. package/src/guidance.ts +35 -0
  37. package/src/index.ts +365 -0
  38. package/src/loopback.ts +48 -0
  39. package/src/node-runtime.ts +120 -0
  40. package/src/routes.ts +377 -0
  41. package/src/skills-content.ts +309 -0
  42. package/src/skills.ts +91 -0
  43. package/test/config-values.test.ts +60 -0
  44. package/test/design-intake.test.ts +40 -0
  45. package/test/design-rules.test.ts +72 -0
  46. package/test/eda-launch.test.ts +114 -0
  47. package/test/extension-package.test.ts +27 -0
  48. package/test/extension-routes.test.ts +116 -0
  49. package/test/netlist-erc.test.ts +90 -0
  50. package/test/node-runtime.test.ts +65 -0
  51. package/test/schematic-audit.test.ts +71 -0
  52. package/test/seams.test.ts +164 -0
  53. package/test/skills.test.ts +68 -0
@@ -0,0 +1,160 @@
1
+ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
2
+
3
+ /**
4
+ * Snapshot of one settings namespace as this card consumes it. Declared locally
5
+ * instead of importing DSH's own type so one build spans generations: 0.1.x
6
+ * exported `SettingsScopeSnapshot` from `@deepseek-ai/dsh-client-ui-settings/client`,
7
+ * while 0.2 replaced that scope with `ConfigFormSnapshot` (same fields).
8
+ */
9
+ export interface SettingsScopeSnapshot<T> {
10
+ status: 'loading' | 'ready' | 'unavailable'
11
+ value: T | undefined
12
+ base: unknown
13
+ user: unknown
14
+ revision: number | undefined
15
+ writable: boolean
16
+ mode: 'host' | 'memory'
17
+ }
18
+
19
+ /**
20
+ * The namespace scope this card writes through. Structural for the same reason:
21
+ * 0.1.x `SettingsScope` and 0.2 `ConfigForm` carry these exact members (0.2's
22
+ * writes additionally resolve to a boolean, which this face ignores).
23
+ */
24
+ export interface SettingsScope<T> {
25
+ getSnapshot: () => SettingsScopeSnapshot<T>
26
+ subscribe: (listener: () => void) => () => void
27
+ mutate: (ops: readonly SettingsOp[], expectedRevision?: number) => Promise<void>
28
+ set: (field: string, value: unknown) => Promise<void>
29
+ unset: (field: string) => Promise<void>
30
+ }
31
+
32
+ interface BridgeView {
33
+ ns: string
34
+ value: unknown
35
+ base?: unknown
36
+ user?: unknown
37
+ revision: number
38
+ secrets?: Array<{ path: string[]; set: boolean }>
39
+ }
40
+
41
+ interface DescribeResponse {
42
+ namespaces: BridgeView[]
43
+ writable: boolean
44
+ }
45
+
46
+ interface MutateResponse {
47
+ ok: boolean
48
+ value?: BridgeView
49
+ code?: string
50
+ message?: string
51
+ }
52
+
53
+ interface SettingsOp {
54
+ op: 'set' | 'unset'
55
+ path: string[]
56
+ value?: unknown
57
+ }
58
+
59
+ const API = {
60
+ describe: '/api/dsh-eda-mcp/settings/describe',
61
+ mutate: '/api/dsh-eda-mcp/settings/mutate',
62
+ } as const
63
+
64
+ /**
65
+ * A minimal SettingsScope backed by the dsh-eda-mcp Host settings bridge.
66
+ * Mirrors the official settings apiproxy shape so the Web GUI card can read and
67
+ * write the plugin namespace without depending on apiproxy exposing it.
68
+ */
69
+ export function createEdaMcpSettingsScope<T>(): SettingsScope<T> {
70
+ const store = createSnapshotStore<SettingsScopeSnapshot<T>>({
71
+ status: 'loading',
72
+ value: undefined,
73
+ base: undefined,
74
+ user: undefined,
75
+ revision: undefined,
76
+ writable: false,
77
+ mode: 'host',
78
+ })
79
+
80
+ let tail = Promise.resolve()
81
+ let disposed = false
82
+
83
+ const post = async (path: string, body: unknown): Promise<unknown> => {
84
+ const response = await fetch(path, {
85
+ method: 'POST',
86
+ headers: { 'content-type': 'application/json' },
87
+ body: JSON.stringify(body),
88
+ })
89
+ if (!response.ok) throw new Error('HTTP ' + response.status)
90
+ return await response.json()
91
+ }
92
+
93
+ const read = async (): Promise<void> => {
94
+ if (disposed) return
95
+ try {
96
+ const body = await post(API.describe, {}) as { ok?: boolean; value?: DescribeResponse }
97
+ if (body.ok !== true || body.value === undefined) throw new Error('settings bridge unavailable')
98
+ const view = body.value.namespaces.find(candidate => candidate.ns === 'eda-mcp')
99
+ if (view === undefined) throw new Error('eda-mcp settings namespace not exposed')
100
+ accept(view, body.value.writable)
101
+ } catch {
102
+ if (!disposed) store.update((draft) => { draft.status = 'unavailable' })
103
+ }
104
+ }
105
+
106
+ const accept = (view: BridgeView, writable: boolean): void => {
107
+ if (disposed) return
108
+ store.set({
109
+ status: 'ready',
110
+ value: view.value as T | undefined,
111
+ base: view.base,
112
+ user: view.user,
113
+ revision: view.revision,
114
+ writable,
115
+ mode: 'host',
116
+ })
117
+ }
118
+
119
+ const write = async (ops: SettingsOp[], expectedRevision?: number): Promise<void> => {
120
+ if (disposed) return
121
+ const revision = expectedRevision ?? store.getSnapshot().revision
122
+ try {
123
+ const body = await post(API.mutate, {
124
+ ns: 'eda-mcp',
125
+ ops,
126
+ ...(revision === undefined ? {} : { expectedRevision: revision }),
127
+ }) as MutateResponse
128
+ if (body.ok !== true || body.value === undefined) {
129
+ await read()
130
+ throw new Error(body.message ?? body.code ?? 'settings write failed')
131
+ }
132
+ accept(body.value, store.getSnapshot().writable)
133
+ } catch {
134
+ await read().catch(() => {})
135
+ throw new Error('settings write failed')
136
+ }
137
+ }
138
+
139
+ const enqueue = (operation: () => Promise<void>): Promise<void> => {
140
+ if (disposed) return Promise.resolve()
141
+ const task = tail.then(operation, operation)
142
+ tail = task.catch(() => {})
143
+ return task
144
+ }
145
+
146
+ void read()
147
+
148
+ return {
149
+ getSnapshot: () => store.getSnapshot(),
150
+ subscribe: listener => store.subscribe(listener),
151
+ mutate: (ops, expectedRevision) => enqueue(() => write(
152
+ ops.map(op => (op.op === 'set'
153
+ ? { op: 'set' as const, path: [...op.path], value: op.value }
154
+ : { op: 'unset' as const, path: [...op.path] })),
155
+ expectedRevision,
156
+ )),
157
+ set: (field, value) => enqueue(() => write([{ op: 'set', path: [field], value }])),
158
+ unset: field => enqueue(() => write([{ op: 'unset', path: [field] }])),
159
+ }
160
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Config-value normalization for the DSH settings generations.
3
+ *
4
+ * DSH >= 0.2 hands a plugin's `volatile` config fields over as live references
5
+ * instead of plain values. `@deepseek-ai/cosmokit` builds them as
6
+ * `Object.freeze({ get: () => current, [write]: (value) => { current = value } })`
7
+ * with `const write = Symbol.for("cosmokit.volatile.write")`, and marks them with
8
+ * `isVolatile(value) = typeof value === "object" && value !== null && write in value`.
9
+ *
10
+ * `@deepseek-ai/dsh-settings` folds those references with
11
+ * `isVolatile(value) ? value.get() : value` before serializing. A plugin that
12
+ * consumes a handle directly sees `{}` for a number field, and `"[object
13
+ * Object]"` once stringified — exactly how a config validation failure silently
14
+ * stopped the bridge spawn.
15
+ *
16
+ * The marker is looked up through the global symbol registry, so this needs no
17
+ * dependency on cosmokit (nor on the copy the host happened to load).
18
+ */
19
+
20
+ /** The shared reference marker (`Symbol.for` keeps one instance per process). */
21
+ const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write')
22
+
23
+ /** Whether a value is one of those live references. */
24
+ export function isLiveValue(value: unknown): value is { get: () => unknown } {
25
+ if (value === null || typeof value !== 'object') return false
26
+ return VOLATILE_WRITE in value
27
+ }
28
+
29
+ /** Resolve one config field to its plain value; other generations pass through. */
30
+ export function readConfigValue(value: unknown): unknown {
31
+ if (!isLiveValue(value)) return value
32
+ try {
33
+ return value.get()
34
+ } catch {
35
+ return value
36
+ }
37
+ }
38
+
39
+ /** Resolve every own enumerable field of a config object. */
40
+ export function unwrapConfig<T extends object>(source: T): T {
41
+ const plain: Record<string, unknown> = {}
42
+ for (const [key, value] of Object.entries(source)) plain[key] = readConfigValue(value)
43
+ return plain as T
44
+ }
45
+
46
+ /**
47
+ * Read a boolean config field, falling back to the default when the value is not
48
+ * a boolean — so a future settings generation that hands over a new wrapper can
49
+ * never push an object into a consumer that validates types.
50
+ */
51
+ export function booleanField(value: unknown, fallback: boolean): boolean {
52
+ const plain = readConfigValue(value)
53
+ return typeof plain === 'boolean' ? plain : fallback
54
+ }
55
+
56
+ /** Read a number config field, falling back to the default for non-numbers. */
57
+ export function numberField(value: unknown, fallback: number): number {
58
+ const plain = readConfigValue(value)
59
+ return typeof plain === 'number' && Number.isFinite(plain) ? plain : fallback
60
+ }
@@ -0,0 +1,35 @@
1
+ /** Order of the announcement section within the tool-guidance band. */
2
+ export const SECTION_ORDER = 211
3
+
4
+ /**
5
+ * Injected into every request when `announceToAgent` is on.
6
+ *
7
+ * It is a system-prompt section, so it stays short: the normative rule set lives
8
+ * in `docs/design-rules.md`, and the numeric limits are enforced by the tools
9
+ * themselves (see `src/bridge/design-rules.ts`), which is why this text names the
10
+ * behaviour instead of repeating every table.
11
+ */
12
+ export const EDA_MCP_GUIDANCE = [
13
+ '本机已安装 dsh-eda-mcp 插件(DSH ↔ 嘉立创EDA专业版 MCP 画图),工具名形如 mcp__jlceda__eda_place_component / mcp__jlceda__pcb_draw_track。',
14
+ '必须遵守的设计规范:docs/design-rules.md(仓库内),可量化部分由工具强制:',
15
+ '· 网络名只允许字母、数字、下划线、点、加号、减号,最长 255 字符;出现空格、斜杠、括号、中文会被拒绝(JLC 后端按精确字符串匹配,特殊字符会把网络拆散或丢失)。差分对写成 USB_DP / USB_DM 两个网络,不要写 USB_DP/DM。',
16
+ '· PCB 走线线宽:普通信号 ≥6mil(0.15mm),器件到去耦电容的分支电源 10mil,主干电源 16mil,>500mA 或 GND 走线 20mil。pcb_draw_track 不传 lineWidth 时按网络角色给默认值,低于 6mil 直接报错(确需用 force:true)。',
17
+ '· 过孔:常规信号 0.2/0.4mm、电源/GND 0.3/0.6mm、大电流 0.4/0.8mm;焊环 ≥0.2mm 强制,孔径 <0.3mm 会警告(免费打样下限)。pcb_draw_via 不传尺寸时按角色给标准孔径,不要自造非标尺寸。',
18
+ '· 铺铜:顶层/底层铺 GND 铜,铺铜与其它网络间距 ≥6mil(建议 10mil,在 设计→设计规则 里设置),导出前移除孤岛。',
19
+ '· 流程:原理图分区(电源/主控/接口/信号处理,左输入右输出、上电源下地,主控居中、去耦与晶振贴芯片、区域用折线框+文本标注)→ 原理图 DRC → 布局传递/布局(安装孔→板边接口→主控→配套器件,去耦电容距引脚 ≤2mm,晶振靠芯片且区域净空,模拟/数字分开)→ 设置线宽线距过孔规则 → 布线 → 铺铜 → PCB DRC → 丝印(高度 ≥1mm、线宽 ≥0.15mm、方向统一不压焊盘)与锁定板框 → 导出 Gerber/BOM/装配文件。',
20
+ '· 布线前先调 eda_design_audit 做只读体检(线宽/过孔/网络名/板框/铺铜/DRC 逐项给结论),布线后再调一次;eda_pcb_run_drc 是真 DRC,不能跳过。',
21
+ '绘制细节:原理图坐标为 0.01inch,原点在 A4 图框左下角,y 向上,图框 x 0~1170、y 0~825,标题栏 x 460~1160、y 10~190 必须避让(先 eda_get_page_info)。PCB 坐标为 mil。板框用 pcb_draw_board_outline(板框层 11 的一条 pcb_PrimitivePolyline,线宽默认 10mil);区域只能用铜层 top/bottom/内层(15–44)/MULTI(12)。',
22
+ '长任务:eda_pcb_auto_route 默认异步启动(EDA 自己显示进度条),必须用 eda_pcb_job_status 轮询 running 直到 false,不要加大超时;eda_pcb_clear_routing 同理(旧扩展自动分批,按 done 继续调用)。',
23
+ '原理图 API(sch_Net.*、网表导出)只作用于当前活动文档:返回空时先用 eda_get_active_document 查、eda_open_document 切到原理图页。',
24
+ '生效范围(改动不热更新):插件源码 src/ 改动要 node build.mjs 后重启 DSH,当前会话不会生效;扩展 jlc-extension/ 改动要重新导入 dsh-eda-bridge-extension-<版本>.zip 并重启嘉立创EDA(eda_status 的 extensionVersions 必须与 bridgeVersion 一致);只有重启桥接子进程能由 agent 自己做(POST /api/dsh-eda-mcp/reconnect)。排查出口:/api/dsh-eda-mcp/diagnostics 的 clientStartupError / skills / bridgeHealth。扩展版本只递增最小位。',
25
+ '开工前先问参数:用户说"画一块 X 板"时不要直接摆器件——先调 eda_design_intake 拿问卷(供电/电流、主控与时钟、烧写接口、对外接口与隔离、板框尺寸与定位孔、连接器朝向、层数与铜厚、贴片方式、交付程度),critical 项用 ask_user_question 一次问清(有 options 就给选项),不要自己编默认值当作已知;只有 non-critical 项可用 fallback。eda_place_component 在未确认参数时会返回 intakeWarning 提醒。',
26
+ '交付前必须跑 eda_delivery_checklist(ERC + PCB 审计/DRC + Gerber + BOM 一次串完,可 outPath 落 Markdown 报告),返回 ok:true 才算可下单;原理图几何问题用 eda_schematic_audit(出框/压标题栏/符号重叠/偏栅格),参数答复由 eda_design_intake 写进工程描述持久化。',
27
+ '电气正确性不要指望 DRC:原理图 DRC 在这台构建上只回聚合计数。布线/投板前跑 eda_netlist_erc(网表级只读烟雾测试:位号重复、悬空脚、单端点网络、器件短路、电源脚/去耦、USB D± 成对、晶振负载电容、复位 RC、BOOT 下拉、Type-C CC 下拉),它挡住的是"DRC 干净但电路错"这一类事故(公开横评里 AI 画板的典型翻车点)。',
28
+ '原理图工作规范(默认手工,禁止为省事用自动布局/自动布线):按 10 单位栅格对齐;信号左→右、电源在上、地在下;器件间留 ≥20 单位走线与标签空间;先 eda_get_page_info 看安全区再摆位;摆完用 eda_get_components 检查包围盒不重叠。eda_auto_layout / eda_auto_route 默认被拒绝(需 force:true 且设置里放行),仅当用户明确要求时使用;版面检查优先"导出图片自行识别"而不是让 EDA 重排。',
29
+ '跨区域同名网络必须用 eda_place_net_port / 网络标签:eda_draw_wire 的 net 只对悬空导线有效,导线一旦接触引脚,EDA 会按连通性重算网络名(实测 TESTNET 被并入 LED_A),所以"同名导线 = 同名网络"不成立。',
30
+ '网络标签:eda_place_net_label 先真实调 createNetLabel,该 API 在 3.2.186 上不响应 → 探测结论按会话缓存后自动降级为纯文本标签(无电气语义,靠 stub 导线承载网络);批量务必用 eda_place_net_labels 一次调用,不要串行上百次(会打爆 run_code 超时且没有进度)。标签可枚举/清理:eda_get_net_labels + eda_delete_primitive(kind: netlabel|netport|netflag|text)。',
31
+ '看图判据(eda_capture + 图片读取):只在 4 个时刻必看——布局完成待布线、布线完成待 DRC、丝印/工艺文字放完、坐标结果与直觉冲突时;不要每改一个图元截一次,也不要为确认返回值/属性看图(用 eda_get_* 更准)。单次约 2.7 s、0.4 MB;PNG 属临时文件,看完立刻 eda_capture({cleanup:true}) 删除,不在磁盘留截图。',
32
+ '引脚身份用 eda_get_pins 一次拿全(含 pinName/pinNumber),不要逐脚调 raw sch_PrimitivePin.get;原理图挪器件用 eda_move_component(保 designator/value),不要删了重放。完整工作手册:调 eda_workflow_guide。',
33
+ '连接问题先调 eda_status:connectedClients=0 表示 EDA 未连接(确认 EDA 已打开、扩展已导入并开启「允许外部交互」、端口 39009 空闲);extensionVersion 与 bridgeVersion 不一致或报 API method not allowed 表示扩展是旧版,需要重新导入 dsh-eda-bridge-extension.zip 并重启 EDA。',
34
+ 'PCB 坐标有两套:EDA 界面显示的是画布原点坐标,而所有 API 用的是数据原点坐标,两者差一个偏移(官方 API 注释原文)。按界面读出的坐标直接喂给工具会偏 —— 先用 eda_pcb_canvas_origin 查偏移,或 align:true 调 setCanvasOrigin(0,0) 让显示与 API 一致;原理图侧没有这个偏移。',
35
+ ].join('\n')
package/src/index.ts ADDED
@@ -0,0 +1,365 @@
1
+ import type { Context } from '@deepseek-ai/cordis'
2
+ import type {} from '@deepseek-ai/dsh-host-webserver'
3
+ import type {} from '@deepseek-ai/dsh-system-prompt'
4
+ import type {} from '@deepseek-ai/dsh-settings'
5
+ import * as mcpClient from '@deepseek-ai/dsh-mcp-client'
6
+ import z from '@deepseek-ai/schemastery'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { existsSync, readFileSync } from 'node:fs'
9
+ import { dirname } from 'node:path'
10
+ import { EDA_MCP_GUIDANCE, SECTION_ORDER } from './guidance.ts'
11
+ import { createEdaSkillProvider, EDA_SKILL_NAME } from './skills.ts'
12
+ import { makeEdaMcpRoutes, makeEdaMcpSettingsRoutes, type SettingsBridge } from './routes.ts'
13
+ import { resolveBridgeRuntime } from './node-runtime.ts'
14
+ import { BridgeDiagnostics } from './bridge-diagnostics.ts'
15
+ import { unwrapConfig, booleanField, numberField } from './config-values.ts'
16
+
17
+ /** Settings namespace owned by this plugin (a lowercase hyphenated id since DSH 0.1.5). */
18
+ export const EDA_MCP_SETTINGS_NAMESPACE = 'eda-mcp'
19
+
20
+ export interface EdaMcpConfig {
21
+ enabled?: boolean
22
+ announceToAgent?: boolean
23
+ toolCallTimeoutMs?: number
24
+ allowRawApi?: boolean
25
+ /** Path to lceda-pro.exe; empty lets eda_launch discover it. */
26
+ edaExecutable?: string
27
+ /** Allow eda_auto_layout / eda_auto_route (off by default: place and route by hand). */
28
+ allowAutoLayoutRouting?: boolean
29
+ }
30
+
31
+ /**
32
+ * Schema of this plugin's profile entry Config — which IS its settings namespace
33
+ * on DSH >= 0.2, where only fields marked `volatile` become live-editable form
34
+ * fields (every field here is applied without a restart). The marker is inert
35
+ * metadata on the older settings seams.
36
+ */
37
+ export const Config = z.object({
38
+ enabled: z.boolean().default(true).volatile(),
39
+ announceToAgent: z.boolean().default(true).volatile(),
40
+ toolCallTimeoutMs: z.number().min(1000).max(300000).default(60000).volatile(),
41
+ allowRawApi: z.boolean().default(true).volatile(),
42
+ /** Optional path to lceda-pro.exe; empty means "let eda_launch discover it". */
43
+ edaExecutable: z.string().default('').volatile(),
44
+ /**
45
+ * Automatic schematic layout/routing stays off unless enabled here: the default
46
+ * working style is grid-aligned manual placement plus a visual check.
47
+ */
48
+ allowAutoLayoutRouting: z.boolean().default(false).volatile(),
49
+ })
50
+
51
+ /** Hooks a settings registration hands to the DSH settings seam. */
52
+ interface SettingsSectionHooks<T> {
53
+ setSource: (source: () => T) => void
54
+ onChange: () => void
55
+ }
56
+
57
+ /**
58
+ * Unwrap one config field.
59
+ *
60
+ * DSH >= 0.2 hands `volatile` fields over as live value references instead of
61
+ * plain values (see `./config-values.ts`); consuming the handle directly made
62
+ * `toolCallTimeoutMs` a `{}` and turned env values into `"[object Object]"`,
63
+ * which failed the mcp-client's config validation so the bridge was never
64
+ * spawned. Older generations pass plain values, which this leaves untouched.
65
+ */
66
+
67
+ /** Owner handle of one registered namespace, as both settings generations expose it. */
68
+ interface SettingsScopeHandle<T> {
69
+ get: () => T
70
+ watch: (callback: () => void) => () => void
71
+ }
72
+
73
+ /**
74
+ * The provider faces this registration probes at runtime, newest first:
75
+ *
76
+ * - `configure` (DSH >= 0.2 `SettingsForms`): a plugin's settings namespace IS its
77
+ * profile entry Config, so there is no namespace to register — only the
78
+ * automatic-page policy is ours to set.
79
+ * - `installSection` (DSH >= 0.1.5): the old free `installSettingsSection` moved
80
+ * onto the provider.
81
+ * - `register` (<= 0.1.1): what that free function used internally.
82
+ */
83
+ interface SettingsProviderFaces<T> {
84
+ configure?: (presentation: { auto?: boolean }) => () => void
85
+ installSection?: (owner: Context, ns: string, schema: unknown, entry: T, hooks: SettingsSectionHooks<T>) => void
86
+ register?: (ns: string, schema: unknown, options: { base: T }) => SettingsScopeHandle<T>
87
+ }
88
+
89
+ /** Fiber states meaning "this plugin is tearing down" (value mirror of FiberState). */
90
+ const FIBER_DISPOSED = 4
91
+ const FIBER_UNLOADING = 5
92
+
93
+ /** Whether the owning plugin's fiber is unloading or already disposed. */
94
+ function isUnloading(ctx: Context): boolean {
95
+ const state = (ctx as unknown as { fiber?: { state?: number } }).fiber?.state
96
+ return state === FIBER_UNLOADING || state === FIBER_DISPOSED
97
+ }
98
+
99
+ /**
100
+ * Register this plugin's settings namespace on whichever settings seam the
101
+ * running DSH exposes, so one build serves every generation:
102
+ *
103
+ * - DSH >= 0.2: nothing to register (the entry Config is the namespace); the
104
+ * automatic settings page is switched off so the shipped card is the only page.
105
+ * - the pre-0.1.5 wiring over `settings.register(ns, schema, { base })`, which is
106
+ * exactly what the removed free `installSettingsSection` did: point the source
107
+ * thunk at the resolved scope, fall back to the composition entry when the
108
+ * scope detaches, and re-run `onChange` on every committed change.
109
+ *
110
+ * @param ctx - the plugin context owning the section (its unload releases it).
111
+ * @param scoped - the settings-service context the registration rides.
112
+ * @param ns - this plugin's settings namespace id.
113
+ * @param schema - schemastery schema resolving the namespace value.
114
+ * @param entry - composition entry used as the base layer and fallback value.
115
+ * @param hooks - source sink and change notification.
116
+ */
117
+ function installSettingsSection<T>(ctx: Context, scoped: Context, ns: string, schema: unknown, entry: T, hooks: SettingsSectionHooks<T>): void {
118
+ const provider = scoped.settings as unknown as SettingsProviderFaces<T>
119
+ if (typeof provider.configure === 'function') {
120
+ // DSH >= 0.2: the entry Config in the profile patch is this plugin's settings
121
+ // namespace and the Loader re-applies the plugin on every committed change, so
122
+ // the apply() argument is authoritative — nothing to register. Suppress the
123
+ // auto-generated page because this plugin ships its own settings card.
124
+ ctx.effect(() => provider.configure!({ auto: false }), 'dsh-eda-mcp: settings page policy')
125
+ hooks.onChange()
126
+ return
127
+ }
128
+ if (typeof provider.installSection === 'function') {
129
+ provider.installSection(ctx, ns, schema, entry, hooks)
130
+ return
131
+ }
132
+ if (typeof provider.register === 'function') {
133
+ const scope = provider.register(ns, schema, { base: entry })
134
+ hooks.setSource(() => scope.get())
135
+ scoped.effect(() => () => {
136
+ if (isUnloading(ctx)) return
137
+ hooks.setSource(() => entry)
138
+ hooks.onChange()
139
+ })
140
+ hooks.onChange()
141
+ scope.watch(() => {
142
+ if (isUnloading(ctx)) return
143
+ hooks.onChange()
144
+ })
145
+ return
146
+ }
147
+ throw new TypeError('dsh-eda-mcp: the running dsh settings service exposes none of configure (>= 0.2), installSection (>= 0.1.5), register (<= 0.1.1)')
148
+ }
149
+
150
+ export const inject = ['webServer', 'systemPrompt']
151
+
152
+ const BRIDGE_URL = new URL('../lib/bridge.mjs', import.meta.url)
153
+
154
+ /**
155
+ * The extension zip is shipped as `dsh-eda-bridge-extension-<version>.zip` (the
156
+ * version is the wire contract in jlc-extension/extension.json). Resolve it from
157
+ * that manifest instead of hard-coding a file name; older layouts without a
158
+ * versioned file keep working through the plain-name fallback.
159
+ */
160
+ function resolveExtensionVersion(): string {
161
+ try {
162
+ const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../jlc-extension/extension.json', import.meta.url)), 'utf8')) as { version?: string }
163
+ return typeof manifest.version === 'string' ? manifest.version : ''
164
+ } catch {
165
+ return ''
166
+ }
167
+ }
168
+
169
+ /** Bridge script path, resolved once. */
170
+ const BRIDGE_PATH = fileURLToPath(BRIDGE_URL)
171
+
172
+ /**
173
+ * Launch description of the bridge child: the executable that can actually run
174
+ * `lib/bridge.mjs` (see `resolveBridgeRuntime`) plus this plugin's settings.
175
+ *
176
+ * `failOnStartupError: true` makes a failed initial connection reject the client
177
+ * fiber instead of only logging to the host logger — the desktop app writes no
178
+ * host log to disk, so a silent failure there is invisible. The bridge is this
179
+ * plugin's own script, so a startup failure is always a real fault worth raising.
180
+ */
181
+ function bridgeLaunchFor(active: EdaMcpConfig) {
182
+ const runtime = resolveBridgeRuntime()
183
+ // The typed accessors resolve a live reference if one is still present and fall
184
+ // back to the schema default otherwise, so a stale wrapper can never produce a
185
+ // client config that fails validation.
186
+ const allowRawApi = booleanField(active.allowRawApi, true)
187
+ const allowAutoLayoutRouting = booleanField(active.allowAutoLayoutRouting, false)
188
+ const toolCallTimeoutMs = numberField(active.toolCallTimeoutMs, 60000)
189
+ return {
190
+ transport: 'stdio' as const,
191
+ serverName: 'jlceda',
192
+ command: runtime.command,
193
+ args: [BRIDGE_PATH],
194
+ env: {
195
+ ...runtime.extraEnv,
196
+ DSH_EDA_MCP_ALLOW_RAW_API: allowRawApi ? '1' : '0',
197
+ DSH_EDA_ALLOW_AUTO_LAYOUT: allowAutoLayoutRouting ? '1' : '0',
198
+ DSH_EDA_MCP_TOOL_TIMEOUT_MS: String(toolCallTimeoutMs),
199
+ // eda_launch falls back to the registry / install dirs / PATH when empty.
200
+ DSH_EDA_EXECUTABLE: typeof active.edaExecutable === 'string' ? active.edaExecutable : '',
201
+ },
202
+ cwd: dirname(BRIDGE_PATH),
203
+ toolCallTimeoutMs,
204
+ failOnStartupError: true,
205
+ reconnect: {
206
+ enabled: true,
207
+ initialDelayMs: 500,
208
+ maxDelayMs: 30000,
209
+ maxAttempts: 10,
210
+ },
211
+ }
212
+ }
213
+
214
+ /** Diagnostics for the routes: which executable the bridge child is started with. */
215
+ function describeBridgeLaunch(): { command: string; args: string[]; source: string } {
216
+ const runtime = resolveBridgeRuntime()
217
+ return { command: runtime.command, args: [BRIDGE_PATH], source: runtime.source }
218
+ }
219
+
220
+ export function apply(ctx: Context, config?: EdaMcpConfig): void {
221
+ // Config values always reach the rest of the plugin unwrapped: on DSH >= 0.2
222
+ // `volatile` fields arrive as live value handles.
223
+ /** Skill registration outcome, reported by /api/dsh-eda-mcp/diagnostics. */
224
+ let skillState: { attempted: boolean; registered: boolean; error: string | null; names: string[] } = {
225
+ attempted: false,
226
+ registered: false,
227
+ error: null,
228
+ names: [],
229
+ }
230
+
231
+ let current: () => EdaMcpConfig = () => unwrapConfig(config ?? {})
232
+ let disposeClient: (() => Promise<void>) | undefined
233
+ let disposeSection: (() => void) | undefined
234
+ let mounting: Promise<void> = Promise.resolve()
235
+ let syncedBySettings = false
236
+ const diagnostics = new BridgeDiagnostics()
237
+
238
+ /** Poll the bridge for a while so the diagnostics record reflects reality. */
239
+ const refreshBridgeHealth = (): void => {
240
+ void (async () => {
241
+ for (let attempt = 0; attempt < 12; attempt += 1) {
242
+ if (await diagnostics.probe() === 'ok') return
243
+ await new Promise(resolve => setTimeout(resolve, 1000))
244
+ }
245
+ })()
246
+ }
247
+
248
+ const remountClient = (): void => {
249
+ // Mounts are serialized and awaited: the 0.2 mcp-client reserves its
250
+ // `serverName` for as long as its fiber lives and rejects a second mount of
251
+ // the same name with "already in use", so a remount must not start before the
252
+ // previous fiber finished disposing. `sync()` can run twice at startup.
253
+ mounting = mounting.then(async () => {
254
+ if (disposeClient !== undefined) {
255
+ const dispose = disposeClient
256
+ disposeClient = undefined
257
+ await dispose()
258
+ }
259
+ const active = current()
260
+ if (!(active.enabled ?? true)) return
261
+ diagnostics.beginMount()
262
+ try {
263
+ // `@deepseek-ai/dsh-mcp-client` declares `inject: ['tools']` on DSH >= 0.2, so
264
+ // it only applies where the tool registry is reachable. Injecting here
265
+ // waits for that service and records whether it ever appeared.
266
+ const fiber = ctx.inject(['tools'], (toolsCtx) => {
267
+ diagnostics.recordToolsServiceSeen()
268
+ try {
269
+ const client = toolsCtx.plugin(mcpClient, bridgeLaunchFor(active))
270
+ diagnostics.observeClientFiber(client)
271
+ refreshBridgeHealth()
272
+ } catch (error) {
273
+ diagnostics.recordError(error)
274
+ }
275
+ })
276
+ disposeClient = async () => { await fiber.dispose() }
277
+ } catch (error) {
278
+ diagnostics.recordError(error)
279
+ }
280
+ }).catch((error: unknown) => {
281
+ diagnostics.recordError(error)
282
+ })
283
+ }
284
+
285
+ ctx.effect(() => {
286
+ const disposers = makeEdaMcpRoutes({
287
+ getConfig: () => current(),
288
+ extensionDigestPath: fileURLToPath(new URL('../lib/extension-digest.json', import.meta.url)),
289
+ extensionVersion: resolveExtensionVersion(),
290
+ extensionDownloadBase: process.env.DSH_EDA_EXTENSION_BASE ?? 'http://159.75.130.207/eda/',
291
+ reconnect: remountClient,
292
+ bridgeLaunch: describeBridgeLaunch,
293
+ // Surface the skill registration so "did it register?" is answerable from
294
+ // /api/dsh-eda-mcp/diagnostics instead of guessing from the skill list.
295
+ diagnostics: () => ({ ...diagnostics.liveSnapshot(), skills: skillState }),
296
+ launchConfig: () => bridgeLaunchFor(current()),
297
+ selfTest: async () => {
298
+ const runtime = resolveBridgeRuntime()
299
+ return await diagnostics.selfTest(runtime.command, [BRIDGE_PATH])
300
+ },
301
+ }).map(route => ctx.webServer.register(route))
302
+ return () => { for (const dispose of disposers) dispose() }
303
+ }, 'eda-mcp: host routes')
304
+
305
+ ctx.inject(['settings'], (sctx) => {
306
+ sctx.effect(() => {
307
+ const disposers = makeEdaMcpSettingsRoutes(sctx.settings as unknown as SettingsBridge).map(route => ctx.webServer.register(route))
308
+ return () => { for (const dispose of disposers) dispose() }
309
+ }, 'eda-mcp: settings bridge')
310
+ })
311
+
312
+ // Register the schematic standard as a DSH skill, so it lands in the session skill
313
+ // catalog next to local/project skills and loads on demand with the `skill` tool.
314
+ // Structural typing + a runtime guard keeps older hosts (no skills service) working.
315
+ ctx.inject(['skills'], (sctx) => {
316
+ // Mirrors the reference implementation (dsh matlab-mcp plugin): the registration is
317
+ // an effect, so it is torn down with the plugin instead of leaking a provider.
318
+ sctx.effect(() => {
319
+ const skills = (sctx as unknown as {
320
+ skills?: { registerProvider?: (factory: (control: unknown) => unknown) => () => void }
321
+ }).skills
322
+ if (skills === undefined || typeof skills.registerProvider !== 'function') {
323
+ skillState = { ...skillState, attempted: true, registered: false, error: 'the host exposes no skills service' }
324
+ return () => { /* nothing to undo */ }
325
+ }
326
+ skillState = { ...skillState, attempted: true }
327
+ const dispose = skills.registerProvider(() => {
328
+ const provider = createEdaSkillProvider()
329
+ skillState = { ...skillState, registered: true, error: null, names: [EDA_SKILL_NAME] }
330
+ return provider
331
+ })
332
+ return () => {
333
+ skillState = { ...skillState, registered: false }
334
+ dispose()
335
+ }
336
+ }, 'eda-mcp: schematic skill')
337
+ })
338
+
339
+ const sync = (): void => {
340
+ if (disposeSection !== undefined) {
341
+ disposeSection()
342
+ disposeSection = undefined
343
+ }
344
+ const active = current()
345
+ remountClient()
346
+ if (booleanField(active.enabled, true) && booleanField(active.announceToAgent, true)) {
347
+ disposeSection = ctx.systemPrompt.section({
348
+ name: 'plugin:eda-mcp',
349
+ order: SECTION_ORDER,
350
+ text: EDA_MCP_GUIDANCE,
351
+ })
352
+ }
353
+ }
354
+
355
+ ctx.inject(['settings'], (sctx) => {
356
+ installSettingsSection(ctx, sctx, EDA_MCP_SETTINGS_NAMESPACE, Config, unwrapConfig(config ?? {}), {
357
+ setSource: (source) => { current = () => unwrapConfig(source()) },
358
+ onChange: () => { syncedBySettings = true; sync() },
359
+ })
360
+ })
361
+
362
+ // The settings seam may already have synced (0.2 calls back synchronously from
363
+ // `configure`), and a redundant remount races the previous fiber's disposal.
364
+ if (!syncedBySettings) sync()
365
+ }
@@ -0,0 +1,48 @@
1
+ import type { IncomingMessage } from 'node:http'
2
+
3
+ function isIPv4Loopback(value: string): boolean {
4
+ const parts = value.split('.')
5
+ return parts.length === 4
6
+ && parts[0] === '127'
7
+ && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
8
+ }
9
+
10
+ export function isLoopbackAddress(address: string | undefined): boolean {
11
+ if (address === undefined) return false
12
+ const normalized = address.toLowerCase()
13
+ if (normalized === '::1') return true
14
+ if (normalized.startsWith('::ffff:')) return isIPv4Loopback(normalized.slice('::ffff:'.length))
15
+ return isIPv4Loopback(normalized)
16
+ }
17
+
18
+ function isLoopbackHostname(hostname: string): boolean {
19
+ if (hostname === 'localhost' || hostname === '[::1]') return true
20
+ return isIPv4Loopback(hostname)
21
+ }
22
+
23
+ /**
24
+ * Loopback trust fence: a loopback socket address AND a loopback Host header.
25
+ * X-Forwarded-For is never trusted. When an Origin header is present it must
26
+ * match the Host authority, which is what the browser sends on same-origin
27
+ * POSTs and what our Host-side test-client fetch sends explicitly.
28
+ */
29
+ export function isLoopbackRequest(request: IncomingMessage): boolean {
30
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return false
31
+ const host = request.headers.host
32
+ if (typeof host !== 'string') return false
33
+ let hostUrl: URL
34
+ try {
35
+ hostUrl = new URL('http://' + host)
36
+ } catch {
37
+ return false
38
+ }
39
+ if (!isLoopbackHostname(hostUrl.hostname)) return false
40
+ if (request.headers['sec-fetch-site'] === 'cross-site') return false
41
+ const origin = request.headers.origin
42
+ if (origin === undefined) return true
43
+ try {
44
+ return new URL(origin).host === hostUrl.host
45
+ } catch {
46
+ return false
47
+ }
48
+ }