openshain 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # openshain
2
+
3
+ The `openshain` command: the reference CLI of the openshain agent harness.
4
+
5
+ Part of [openshain](https://github.com/openshain/openshain). Requires Bun 1.3 or later: the package ships TypeScript source. Documentation, in Japanese, lives in the repository.
6
+
7
+ License: Apache-2.0
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "openshain",
3
+ "version": "0.1.0",
4
+ "description": "Reference CLI of the openshain agent harness",
5
+ "keywords": [
6
+ "openshain",
7
+ "agent",
8
+ "runtime",
9
+ "mcp",
10
+ "accounting",
11
+ "japan"
12
+ ],
13
+ "author": "Hiroki Nakatani",
14
+ "license": "Apache-2.0",
15
+ "homepage": "https://github.com/openshain/openshain",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/openshain/openshain.git",
19
+ "directory": "packages/cli"
20
+ },
21
+ "bugs": "https://github.com/openshain/openshain/issues",
22
+ "type": "module",
23
+ "engines": {
24
+ "bun": ">=1.3"
25
+ },
26
+ "files": [
27
+ "src",
28
+ "!src/**/*.test.ts",
29
+ "!src/**/*.test.tsx",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "exports": {
34
+ ".": "./src/index.ts"
35
+ },
36
+ "bin": {
37
+ "openshain": "./src/bin.ts"
38
+ },
39
+ "dependencies": {
40
+ "@modelcontextprotocol/sdk": "1.30.0",
41
+ "@openshain/agent": "0.1.0",
42
+ "@openshain/core": "0.1.0",
43
+ "@openshain/mcp": "0.1.0",
44
+ "@openshain/tools": "0.1.0",
45
+ "ink": "7.1.1",
46
+ "react": "19.2.8"
47
+ },
48
+ "devDependencies": {
49
+ "@types/react": "19.2.14",
50
+ "ink-testing-library": "4.0.0"
51
+ }
52
+ }
package/src/bin.ts ADDED
@@ -0,0 +1,147 @@
1
+ #!/usr/bin/env bun
2
+ import { createInterface } from "node:readline/promises";
3
+ import { parseArgs } from "node:util";
4
+ import { anthropicProvider, openaiCompatibleProvider } from "@openshain/agent";
5
+ import { isOpenshainError, type RuntimeProviders } from "@openshain/core";
6
+ import { standardTools } from "@openshain/tools";
7
+ import { init } from "./commands/init.ts";
8
+ import { mcp } from "./commands/mcp.ts";
9
+ import { run } from "./commands/run.ts";
10
+ import { toolsList } from "./commands/tools.ts";
11
+ import { workList, workResume, workShow } from "./commands/work.ts";
12
+ import { plain } from "./format.ts";
13
+ import { errorLabel } from "./labels.ts";
14
+ import { startTui } from "./tui/index.ts";
15
+ import { findWorkspace } from "./workspace.ts";
16
+
17
+ const USAGE = `使い方:
18
+ openshain 端末で対話を始める
19
+ openshain init openshain.yaml のひな型を書く
20
+ openshain run "<依頼>" 依頼を Work として進める
21
+ openshain tools list 使える Tool の一覧
22
+ openshain work list Work の一覧
23
+ openshain work show <id> Work の詳細
24
+ openshain work resume <id> 途中で止まった Work を続ける
25
+ openshain mcp MCP Server を stdio で起動する
26
+
27
+ --workspace <dir> 起点のディレクトリ。省略時はカレントディレクトリ
28
+ init はそこに書き、他のコマンドはそこから上に openshain.yaml を探す`;
29
+
30
+ /** The providers this CLI knows, by the ids used in openshain.yaml. */
31
+ const providers: RuntimeProviders = {
32
+ models: {
33
+ anthropic: (model) => anthropicProvider(model),
34
+ "openai-compatible": (model) => openaiCompatibleProvider(model),
35
+ },
36
+ tools: { standard: () => standardTools() },
37
+ };
38
+
39
+ async function main(argv: string[]): Promise<number> {
40
+ const write = (line: string) => console.log(plain(line));
41
+ let values: { workspace?: string; help?: boolean };
42
+ let positionals: string[];
43
+ try {
44
+ ({ values, positionals } = parseArgs({
45
+ args: argv,
46
+ options: { workspace: { type: "string" }, help: { type: "boolean", short: "h" } },
47
+ allowPositionals: true,
48
+ }));
49
+ } catch (err) {
50
+ const message = err instanceof Error ? err.message : String(err);
51
+ const option = /'(-[^']*)'/.exec(message)?.[1];
52
+ const unknown = (err as { code?: string }).code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" && option;
53
+ write(unknown ? `不明なオプション ${option}` : `引数を解釈できません。${message}`);
54
+ write(USAGE);
55
+ return 2;
56
+ }
57
+ const [command, ...rest] = positionals;
58
+ if (!command && !values.help && process.stdin.isTTY === true && process.stdout.isTTY === true) {
59
+ const workspaceRoot = await findWorkspace(values.workspace ?? process.cwd());
60
+ return startTui({ workspaceRoot, providers });
61
+ }
62
+ if (values.help || !command) {
63
+ write(USAGE);
64
+ return values.help ? 0 : 2;
65
+ }
66
+ switch (command) {
67
+ case "init":
68
+ await init({ workspaceRoot: values.workspace ?? process.cwd(), write });
69
+ return 0;
70
+ case "run": {
71
+ const objective = rest.join(" ").trim();
72
+ if (!objective) {
73
+ write('依頼の文を指定してください。openshain run "今月の経理を進めて" のように。');
74
+ return 2;
75
+ }
76
+ const workspaceRoot = await findWorkspace(values.workspace ?? process.cwd());
77
+ return withTerminal((ask) =>
78
+ run({ workspaceRoot, providers, objective, write, ...(ask && { ask }) }),
79
+ );
80
+ }
81
+ case "mcp": {
82
+ const workspaceRoot = await findWorkspace(values.workspace ?? process.cwd());
83
+ await mcp({ workspaceRoot, providers });
84
+ return 0;
85
+ }
86
+ case "tools": {
87
+ if (rest[0] !== "list") {
88
+ write(USAGE);
89
+ return 2;
90
+ }
91
+ const workspaceRoot = await findWorkspace(values.workspace ?? process.cwd());
92
+ await toolsList({ workspaceRoot, providers, write });
93
+ return 0;
94
+ }
95
+ case "work": {
96
+ const sub = rest[0];
97
+ const id = rest[1] ?? "";
98
+ if (!(sub === "list" || ((sub === "show" || sub === "resume") && id))) {
99
+ write(USAGE);
100
+ return 2;
101
+ }
102
+ const workspaceRoot = await findWorkspace(values.workspace ?? process.cwd());
103
+ if (sub === "list") {
104
+ await workList({ workspaceRoot, write });
105
+ return 0;
106
+ }
107
+ if (sub === "show") {
108
+ await workShow({ workspaceRoot, id, write });
109
+ return 0;
110
+ }
111
+ return withTerminal((ask) =>
112
+ workResume({ workspaceRoot, providers, id, write, ...(ask && { ask }) }),
113
+ );
114
+ }
115
+ default:
116
+ write(`不明なコマンド ${command}`);
117
+ write(USAGE);
118
+ return 2;
119
+ }
120
+ }
121
+
122
+ /** Runs `fn` with a way to ask the person when a terminal is there to answer; otherwise without one. */
123
+ async function withTerminal(
124
+ fn: (ask?: (question: string) => Promise<string>) => Promise<number>,
125
+ ): Promise<number> {
126
+ // Without a terminal there is no one to answer; the work waits instead.
127
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) return fn();
128
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
129
+ try {
130
+ return await fn((question) => rl.question(`${plain(question)}\n> `));
131
+ } finally {
132
+ rl.close();
133
+ }
134
+ }
135
+
136
+ main(process.argv.slice(2)).then(
137
+ (code) => process.exit(code),
138
+ (err: unknown) => {
139
+ if (isOpenshainError(err)) {
140
+ const heading = errorLabel(err.code);
141
+ console.error(plain(`エラー(${err.code}) ${heading ? `${heading}。` : ""}${err.message}`));
142
+ } else {
143
+ console.error(err);
144
+ }
145
+ process.exit(1);
146
+ },
147
+ );
@@ -0,0 +1,144 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { CONFIG_FILE_NAME, type Language, OpenshainError } from "@openshain/core";
4
+
5
+ /** The company's language for the template: from the OS locale, Japanese unless the locale says otherwise. */
6
+ export function detectLanguage(env: Record<string, string | undefined>): Language {
7
+ const raw = env.LC_ALL || env.LC_MESSAGES || env.LANG || "";
8
+ const code = raw.toLowerCase().split(/[_.@-]/)[0] ?? "";
9
+ if (code === "ja" || code === "" || code === "c" || code === "posix") return "ja";
10
+ return "en";
11
+ }
12
+
13
+ export const configTemplate = (language: Language) => `version: 1
14
+ company:
15
+ name: サンプル株式会社 # 会社名。model に伝わる
16
+ language: ${language} # ja | en。社員エージェントの名前の言語。init が OS の locale から埋める
17
+ principal:
18
+ id: alice # 依頼する人の id。小文字の英数字、_ と -
19
+ name: Alice
20
+ profession:
21
+ id: generic
22
+ # model への指示。100,000 文字まで
23
+ instructions: |
24
+ あなたはこの会社の事務担当です。依頼された作業を、workspace 内のファイルだけを使って進めてください。
25
+ model:
26
+ provider: anthropic # anthropic | openai-compatible
27
+ model: claude-opus-5
28
+ api_key_env: ANTHROPIC_API_KEY # API キーを入れておく環境変数の名前。サーバーを替えるなら変数名も見直す
29
+ # base_url: http://localhost:11434/v1 # openai-compatible のとき
30
+ # options: { effort: high } # provider にそのまま渡す
31
+ tools:
32
+ - provider: standard
33
+ # allow: [fs_list, fs_search, fs_read, csv_read, csv_aggregate, markdown_read, fs_write, csv_write] # 省略時は全部
34
+ # - module: ./tools/my-tool.ts # ToolProvider を default export するモジュール
35
+ limits:
36
+ max_model_calls: 30 # 超えると Work は失敗(上限到達)で止まる
37
+ max_tool_calls: 100
38
+ max_output_tokens: 16000 # model の 1 回の出力の上限
39
+ # debug:
40
+ # persist_raw: true # provider の生の応答を記録に残す
41
+ `;
42
+
43
+ export const CONFIG_TEMPLATE = configTemplate("ja");
44
+
45
+ /** Registers the runtime as a project MCP server for Claude Code. `openshain` must be on PATH. */
46
+ export const MCP_TEMPLATE = `${JSON.stringify(
47
+ { mcpServers: { openshain: { command: "openshain", args: ["mcp"] } } },
48
+ null,
49
+ 2,
50
+ )}\n`;
51
+
52
+ /** What an outside agent reads before working in the folder. Codex reads AGENTS.md; Claude Code reads it through CLAUDE.md. */
53
+ export const AGENTS_TEMPLATE = `# この会社フォルダで働くエージェントへ
54
+
55
+ このフォルダは openshain の Company Workspace です。この指示は、Claude Code や Codex のような外部のエージェントが MCP 経由でこのフォルダを扱うときのものです。\`openshain run\` で Runtime 自身が動くときは、Work の作成と完了を Runtime が行うので、下の work_* の手順は当てはまりません。
56
+
57
+ 会社のファイルの読み書きと集計は openshain の MCP tool で行います。Claude Code や Codex 自身の Read、Write、Bash は会社のファイルには使いません。Runtime を通らなかった操作は記録に残らないためです。
58
+
59
+ - 依頼を受けたら、まず \`work_create\` に依頼の文をそのまま渡して Work を作る
60
+ - ファイルは \`fs_list\`、\`fs_search\`、\`fs_read\`、\`csv_read\`、\`markdown_read\` で見る。合計や件数は \`csv_aggregate\` に任せ、自分で足さない
61
+ - 書くときは \`fs_write\` か \`csv_write\`
62
+ - 終わったら \`work_complete\` に、何をしたかと、書いたファイルを渡す。続けられないときは \`work_fail\`
63
+ - \`openshain.yaml\` と \`work/\` は Runtime のもの。触らない
64
+ `;
65
+
66
+ export const CLAUDE_TEMPLATE = "@AGENTS.md\n";
67
+
68
+ export interface InitOptions {
69
+ workspaceRoot: string;
70
+ write: (line: string) => void;
71
+ }
72
+
73
+ /**
74
+ * Writes the starter files of a company workspace: openshain.yaml, .mcp.json, AGENTS.md and
75
+ * CLAUDE.md. A workspace that already has openshain.yaml is left alone with an error. An existing
76
+ * .mcp.json keeps its servers and gains the openshain entry when it lacks one; any other file that
77
+ * already exists is kept as it is.
78
+ */
79
+ export async function init({ workspaceRoot, write }: InitOptions): Promise<void> {
80
+ const configPath = join(workspaceRoot, CONFIG_FILE_NAME);
81
+ try {
82
+ await writeFile(configPath, configTemplate(detectLanguage(process.env)), { flag: "wx" });
83
+ } catch (err) {
84
+ const code = (err as NodeJS.ErrnoException).code;
85
+ if (code === "EEXIST") {
86
+ throw new OpenshainError("config", `${configPath} はすでにあります。上書きはしません。`);
87
+ }
88
+ if (code === "ENOENT") {
89
+ throw new OpenshainError(
90
+ "config",
91
+ `${workspaceRoot} がありません。先にディレクトリを作ってください。`,
92
+ );
93
+ }
94
+ throw err;
95
+ }
96
+ write(`${configPath} を作りました。`);
97
+ for (const [name, content] of [
98
+ [".mcp.json", MCP_TEMPLATE],
99
+ ["AGENTS.md", AGENTS_TEMPLATE],
100
+ ["CLAUDE.md", CLAUDE_TEMPLATE],
101
+ ] as const) {
102
+ const path = join(workspaceRoot, name);
103
+ try {
104
+ await writeFile(path, content, { flag: "wx" });
105
+ write(`${path} を作りました。`);
106
+ } catch (err) {
107
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
108
+ if (name === ".mcp.json") write(await addToMcpConfig(path));
109
+ else write(`${path} はすでにあるので触りません。`);
110
+ }
111
+ }
112
+ write(
113
+ "company と principal を自分の会社に合わせ、api_key_env に書いた環境変数を設定してから openshain run を実行してください。",
114
+ );
115
+ }
116
+
117
+ /**
118
+ * Adds the openshain server to a .mcp.json that is already there, keeping every other server.
119
+ * A file that cannot be read as JSON is left as it is, and the line says so.
120
+ */
121
+ async function addToMcpConfig(path: string): Promise<string> {
122
+ let parsed: unknown;
123
+ try {
124
+ parsed = JSON.parse(await readFile(path, "utf8"));
125
+ } catch {
126
+ return `${path} はすでにあり、JSON として読めないので触りません。openshain を手で登録してください。`;
127
+ }
128
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
129
+ return `${path} はすでにあり、形が違うので触りません。openshain を手で登録してください。`;
130
+ }
131
+ const config = parsed as { mcpServers?: unknown };
132
+ const servers =
133
+ config.mcpServers && typeof config.mcpServers === "object" && !Array.isArray(config.mcpServers)
134
+ ? (config.mcpServers as Record<string, unknown>)
135
+ : {};
136
+ if (Object.hasOwn(servers, "openshain"))
137
+ return `${path} には openshain がすでにあるので触りません。`;
138
+ const next = {
139
+ ...config,
140
+ mcpServers: { ...servers, openshain: { command: "openshain", args: ["mcp"] } },
141
+ };
142
+ await writeFile(path, `${JSON.stringify(next, null, 2)}\n`, "utf8");
143
+ return `${path} に openshain を足しました。他の項目はそのままです。`;
144
+ }
@@ -0,0 +1,24 @@
1
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
+ import type { RuntimeProviders } from "@openshain/core";
3
+ import { createMcpServer } from "@openshain/mcp";
4
+
5
+ export interface McpOptions {
6
+ workspaceRoot: string;
7
+ providers: RuntimeProviders;
8
+ }
9
+
10
+ /**
11
+ * Serves the workspace over MCP on stdin and stdout until the client hangs up. Nothing else may
12
+ * be written to stdout while it runs; the protocol owns it.
13
+ */
14
+ export async function mcp({ workspaceRoot, providers }: McpOptions): Promise<void> {
15
+ const server = await createMcpServer({ workspaceRoot, tools: providers.tools });
16
+ const transport = new StdioServerTransport();
17
+ await new Promise<void>((resolve) => {
18
+ server.onclose = () => resolve();
19
+ server.connect(transport).catch((err: unknown) => {
20
+ console.error(err instanceof Error ? err.message : String(err));
21
+ resolve();
22
+ });
23
+ });
24
+ }