diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..fa9fe84 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,78 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + check: + name: lint · typecheck · test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 22 + cache: npm + - run: npm ci --ignore-scripts + - run: npm run lint + - name: Typecheck (web) + run: npx tsc --noEmit + - name: Typecheck (MCP) + run: npx tsc --noEmit -p tsconfig.mcp.json + - run: npm run test:unit + + package: + # 把要发布的 npm 包打成 tarball,装进一个空目录,再真实启动一次: + # stdio 握手并列出 32 个工具、HTTP 模式 /healthz 与 initialize。不连接网关。 + name: npm package · ${{ matrix.os }} · node ${{ matrix.node }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + node: [20, 22, 24] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.node }} + cache: npm + - run: npm ci --ignore-scripts + - run: npm run build:npm + - name: Pack + shell: bash + run: | + cd dist/npm + npm pack --pack-destination "$RUNNER_TEMP" + - name: Install the tarball into an empty project and run it + shell: bash + run: | + version=$(node -p "require('./package.json').version") + mkdir "$RUNNER_TEMP/consumer" + cp scripts/smoke-npm-package.mjs "$RUNNER_TEMP/consumer/" + cd "$RUNNER_TEMP/consumer" + npm init -y >/dev/null + npm install "$RUNNER_TEMP/oh-my-sage-mcp-${version}.tgz" --no-audit --no-fund + test "$(npx oh-my-sage-mcp --version)" = "$version" + node smoke-npm-package.mjs "$version" + + docker: + name: docker build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: docker/build-push-action@v7 + with: + context: . + push: false + tags: oh-my-sage-mcp:ci diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..b50c893 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,76 @@ +name: Release + +# 推送 v* 标签时发布 oh-my-sage-mcp 到 npm,并创建 GitHub Release。 +# 标签必须与 package.json 的 version 一致,例如 version 0.1.0 对应标签 v0.1.0。 +# +# 发布使用 npm 可信发布(OIDC),不需要在仓库里保存 npm 令牌。 +# 包的 npm 设置里已登记本仓库的这个工作流(Settings → Trusted Publisher: +# allocnode/oh-my-sage,release.yml),并会自动附带来源证明(provenance)。 + +on: + push: + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: write + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + # 发布产物只能来自标签里的代码,不复用缓存 + cache: "" + + - run: npm ci --ignore-scripts + - run: npm run lint + - run: npx tsc --noEmit -p tsconfig.mcp.json + - run: npm run test:unit + - run: npm run build:npm + + - name: Check the tag matches package.json + id: meta + run: | + version=$(node -p "require('./package.json').version") + echo "version=$version" >> "$GITHUB_OUTPUT" + if [ "$GITHUB_REF_TYPE" = "tag" ] && [ "$GITHUB_REF_NAME" != "v$version" ]; then + echo "::error::标签 $GITHUB_REF_NAME 与 package.json 版本 $version 不一致" + exit 1 + fi + if npm view "oh-my-sage-mcp@$version" version >/dev/null 2>&1; then + echo "published=true" >> "$GITHUB_OUTPUT" + echo "::notice::oh-my-sage-mcp@$version 已在 npm 上,跳过发布" + else + echo "published=false" >> "$GITHUB_OUTPUT" + fi + + - name: Smoke test the packed package + run: | + version=${{ steps.meta.outputs.version }} + (cd dist/npm && npm pack --pack-destination "$RUNNER_TEMP") + mkdir "$RUNNER_TEMP/consumer" + cp scripts/smoke-npm-package.mjs "$RUNNER_TEMP/consumer/" + cd "$RUNNER_TEMP/consumer" + npm init -y >/dev/null + npm install "$RUNNER_TEMP/oh-my-sage-mcp-$version.tgz" --no-audit --no-fund + node smoke-npm-package.mjs "$version" + + - name: Publish to npm + if: steps.meta.outputs.published == 'false' + run: npm publish dist/npm --access public --provenance + + - name: Create the GitHub release + if: github.ref_type == 'tag' + uses: softprops/action-gh-release@v3 + with: + generate_release_notes: true + body: | + ```bash + npx -y oh-my-sage-mcp@${{ steps.meta.outputs.version }} --version + ``` diff --git a/AGENTS.md b/AGENTS.md index 0ef9671..a47b699 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,8 @@ npm run build # Production build # MCP development npm run build:mcp # Build MCP server only -npm link # Link oh-my-sage-mcp command globally +npm link # Link oh-my-sage-mcp command globally (local development) +npm run build:npm # Assemble the publishable oh-my-sage-mcp package in dist/npm # Quality checks npm run lint # ESLint (next/core-web-vitals) @@ -60,12 +61,15 @@ npx tsx --test # Run a single test file **Docs layout**: `README.md` is the landing page and index only; deployment details, client config formats and env vars live in `deploy/README.md`. Keep heavy operational detail out of the root README. -**Configuration** (stdio; the package is not published to npm, so run `npm run build:mcp && npm link` first): +**npm package**: the root `package.json` is the private web app and is never published. `scripts/build-npm-package.mjs` assembles `dist/npm/` as the standalone `oh-my-sage-mcp` package: version from the root `package.json`, dependencies limited to what `dist/mcp` actually requires (shared with the Docker image via `deploy/mcp-runtime-package.mjs`), plus `deploy/install-local.*`, README with absolute image URLs, and LICENSE. `scripts/smoke-npm-package.mjs` installs-and-runs the packed tarball (stdio handshake with 32 tools, HTTP `/healthz` + initialize). CI (`.github/workflows/ci.yml`) runs lint, both typechecks, unit tests, that smoke test on ubuntu/windows/macos × Node 20/22/24, and a Docker build. Release: bump `version` in the root `package.json`, merge, push tag `v`; `.github/workflows/release.yml` publishes via npm trusted publishing (OIDC, no token) and creates the GitHub release. The MCP server reports the package version (`SERVER_VERSION` reads `package.json`), so never hard-code it. + +**Configuration** (stdio; users run the published npm package through `npx`): ```json { "mcpServers": { "oh-my-sage": { - "command": "oh-my-sage-mcp", + "command": "npx", + "args": ["-y", "oh-my-sage-mcp"], "env": { "GATEWAY_URL": "http://192.168.0.5" } } } diff --git a/README.md b/README.md index e060e0b..f3ec5a4 100644 --- a/README.md +++ b/README.md @@ -69,12 +69,14 @@ Oh My Sage 直接连接局域网里的米家中枢网关。你说想要什么效 1. **一台米家中枢网关**,并且已经在米家 App 里开启了「自动化极客版」。 2. **中枢网关的局域网 IP**,比如 `192.168.0.5`。在米家 App 里打开中枢网关(有多个时选主中枢),点右上角「···」进入设置,找到「自动化极客版」,页面上会显示网关地址。电脑要和网关连在同一个局域网里。 -3. **Node.js 18.17 或更高版本**。没装的话去 [nodejs.org](https://nodejs.org/) 下载 LTS 版本,一路下一步就行。装好后在终端里运行 `node -v`,能看到版本号就说明装好了。 +3. **Node.js 20 或更高版本**。没装的话去 [nodejs.org](https://nodejs.org/) 下载 LTS 版本,一路下一步就行。装好后在终端里运行 `node -v`,能看到版本号就说明装好了。 另外,每次连接网关都要一个 **6 位登录码**,也在上面那个「自动化极客版」页面里。到连接的时候再去取:登录码只能用一次,用过(不管成没成功)就作废了。 ### 方式一:在 AI Agent 里用(MCP) +MCP Server 已发布到 npm([`oh-my-sage-mcp`](https://www.npmjs.com/package/oh-my-sage-mcp)),不用下载仓库,AI Agent 会通过 `npx` 自动下载运行。 + #### 最省事:让 AI Agent 帮你装 打开你的 AI Agent,把下面这段话改好网关地址后整段发给它: @@ -82,35 +84,16 @@ Oh My Sage 直接连接局域网里的米家中枢网关。你说想要什么效 ``` 帮我安装这个 MCP Server:https://github.com/allocnode/oh-my-sage -1. 按仓库 README 的「方式一」完成安装、编译和 npm link -2. 把它加进你自己的 MCP 配置,GATEWAY_URL 填 http://192.168.0.5 -3. 把仓库里的 .agents/skills/mijia-automation 整个目录装成你的 Skill -4. 装完告诉我需要重启什么 +1. 把 npm 包 oh-my-sage-mcp 加进你自己的 MCP 配置,用 npx -y oh-my-sage-mcp 启动,GATEWAY_URL 填 http://192.168.0.5 +2. 运行 npx skills add allocnode/oh-my-sage --skill mijia-automation,把规则 Skill 装给你自己 +3. 装完告诉我需要重启什么 ``` -它装完后按提示重启 AI Agent,然后直接跳到下面的 [第 5 步:开始对话](#5-开始对话)。 +它装完后按提示重启 AI Agent,然后直接跳到下面的 [第 4 步:开始对话](#4-开始对话)。 #### 自己动手装 -![安装 MCP Server 并注册为本机后台服务](docs/images/install.webp) - -##### 1. 下载并安装 - -打开终端(Windows 用 PowerShell,macOS 用「终端」),逐行运行: - -```bash -git clone https://github.com/allocnode/oh-my-sage.git -cd oh-my-sage -npm install -npm run build:mcp -npm link -``` - -最后一步完成后,运行 `oh-my-sage-mcp --help`,没有报「找不到命令」就说明装好了。 - -> 这个包没有发布到 npm,所以 `npx oh-my-sage-mcp` 这种写法用不了,一定要先走完上面几步。 - -##### 2. 把它加到 AI Agent 的 MCP 配置里 +##### 1. 把它加到 AI Agent 的 MCP 配置里 在 AI Agent 的设置里找到 MCP(一般叫「MCP」「MCP Servers」或「连接器」),选「手动添加」或「编辑 JSON」,粘贴下面这段,并把 `192.168.0.5` 改成你的中枢网关 IP: @@ -118,7 +101,8 @@ npm link { "mcpServers": { "oh-my-sage": { - "command": "oh-my-sage-mcp", + "command": "npx", + "args": ["-y", "oh-my-sage-mcp"], "env": { "GATEWAY_URL": "http://192.168.0.5" } } } @@ -127,19 +111,23 @@ npm link 大多数 AI Agent 都认这个格式。少数客户端字段名不一样(比如 OpenCode),对应写法见 [deploy/README.md](deploy/README.md#客户端配置)。 -##### 3. 装 Skill +想先确认能不能下载运行,可以在终端里执行 `npx -y oh-my-sage-mcp --version`,打印出版本号就没问题。 -创建和修改规则时,AI Agent 要参考 `.agents/skills/mijia-automation/` 里的节点模板和连接规则。按你的情况三选一: +##### 2. 装 Skill -- **在本仓库目录里打开 AI Agent**,并且它支持 `.agents/skills/`:会自动发现,什么都不用做 -- **支持 Skill 的 AI Agent**:把 `.agents/skills/mijia-automation` **整个目录**复制到它的 skills 目录,比如 `~/.agents/skills/`,Claude Code 是 `~/.claude/skills/` -- **不支持 Skill 的 AI Agent**:把 `SKILL.md` 的内容贴进它的项目规则文件(比如 `AGENTS.md`) +创建和修改规则时,AI Agent 要参考 `mijia-automation` Skill 里的节点模板和连接规则。在终端里运行: -##### 4. 重启 AI Agent +```bash +npx skills add allocnode/oh-my-sage --skill mijia-automation +``` -重启后在 MCP 列表里能看到 `oh-my-sage`,并且显示已连接或有 32 个工具,就说明配置生效了。 +它会问你要装给哪个 AI Agent,选你正在用的那个就行。不支持 Skill 的 AI Agent,可以把 [SKILL.md](.agents/skills/mijia-automation/SKILL.md) 的内容贴进它的项目规则文件(比如 `AGENTS.md`)。 -##### 5. 开始对话 +##### 3. 重启 AI Agent + +重启后在 MCP 列表里能看到 `oh-my-sage`,并且显示已连接或有 32 个工具,就说明配置生效了。第一次启动要从 npm 下载,会多等几秒。 + +##### 4. 开始对话 先在米家 App 的「自动化极客版」页面取一个新的登录码,然后对 AI Agent 说: @@ -163,17 +151,21 @@ npm link | **本机常驻** | 自己一台电脑长期用 | 登录一次,所有客户端共享 | | **私有服务器**(Docker) | 家里有 NAS,多台电脑共用 | 登录一次,所有电脑共享,需要设置访问 token | -本机常驻只要一条命令(在仓库目录里运行): +本机常驻需要先全局安装,再运行包里自带的安装脚本: + +![全局安装 oh-my-sage-mcp 并注册为本机后台服务](docs/images/install.webp) ```bash +npm install -g oh-my-sage-mcp + # Windows(PowerShell) -pwsh deploy/install-local.ps1 -GatewayUrl http://192.168.0.5 +pwsh "$(npm root -g)/oh-my-sage-mcp/deploy/install-local.ps1" -GatewayUrl http://192.168.0.5 # macOS / Linux -bash deploy/install-local.sh -g http://192.168.0.5 +bash "$(npm root -g)/oh-my-sage-mcp/deploy/install-local.sh" -g http://192.168.0.5 ``` -装完会打印一段配置,把它粘贴到 AI Agent 的 MCP 设置里,替换掉第 2 步的那段即可。Docker 部署、全部参数和排障见 [deploy/README.md](deploy/README.md)。 +装完会打印一段配置,把它粘贴到 AI Agent 的 MCP 设置里,替换掉第 1 步的那段即可。以后升级先运行 `npm install -g oh-my-sage-mcp`,再把上面的安装脚本运行一次,它会重启后台服务换上新版本。Docker 部署、全部参数和排障见 [deploy/README.md](deploy/README.md)。 ### 方式二:网页版 @@ -446,7 +438,7 @@ off set 客厅吸顶灯 2/1 = false 这是 stdio 方式的特点,进程跟着客户端一起退出。改用「本机常驻」或「私有服务器」,网关只登录一次。 **AI 说创建规则需要 Skill?** -AI Agent 没读到 `mijia-automation` Skill,按 [快速开始](#快速开始) 第 3 步装好再试。 +AI Agent 没读到 `mijia-automation` Skill,按 [快速开始](#快速开始) 方式一的第 2 步装好再试。 --- diff --git a/deploy/README.md b/deploy/README.md index 0a9ec3d..1295599 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -22,16 +22,18 @@ oh-my-sage 的 MCP Server 有三种部署方式,工具和功能完全相同, ## 方式二:本机常驻 -注册为当前用户登录时自动启动的后台服务,只监听回环地址,默认端口 `3790`。前提是已构建: +注册为当前用户登录时自动启动的后台服务,只监听回环地址,默认端口 `3790`。安装脚本随 npm 包一起发布,先全局安装: ```bash -npm run build:mcp +npm install -g oh-my-sage-mcp ``` +下面命令里的 `$(npm root -g)/oh-my-sage-mcp` 是全局安装目录。从仓库源码安装时,先在仓库根目录执行 `npm run build:mcp`,再把路径换成仓库里的 `deploy/` 即可。升级时重新 `npm install -g oh-my-sage-mcp`,再运行一次安装脚本。 + ### macOS / Linux ```bash -bash deploy/install-local.sh -g http://192.168.0.5 +bash "$(npm root -g)/oh-my-sage-mcp/deploy/install-local.sh" -g http://192.168.0.5 ``` | 参数 | 说明 | @@ -48,7 +50,7 @@ bash deploy/install-local.sh -g http://192.168.0.5 ### Windows ```powershell -pwsh deploy/install-local.ps1 -GatewayUrl http://192.168.0.5 +pwsh "$(npm root -g)/oh-my-sage-mcp/deploy/install-local.ps1" -GatewayUrl http://192.168.0.5 ``` | 参数 | 说明 | @@ -97,7 +99,8 @@ cd deploy && docker compose up -d --build { "mcpServers": { "oh-my-sage": { - "command": "oh-my-sage-mcp", + "command": "npx", + "args": ["-y", "oh-my-sage-mcp"], "env": { "GATEWAY_URL": "http://192.168.0.5" } } } @@ -111,14 +114,16 @@ cd deploy && docker compose up -d --build "mcp": { "oh-my-sage": { "type": "local", - "command": ["oh-my-sage-mcp"], + "command": ["npx", "-y", "oh-my-sage-mcp"], "environment": { "GATEWAY_URL": "http://192.168.0.5" } } } } ``` -区别只在配置文件位置、外层键名和数组/字符串写法,`command` 与 `GATEWAY_URL` 的取值不变。其他客户端按各自文档对应填写。 +区别只在配置文件位置、外层键名和数组/字符串写法,启动命令与 `GATEWAY_URL` 的取值不变。其他客户端按各自文档对应填写。 + +已经 `npm install -g oh-my-sage-mcp` 全局安装的,可以把启动命令换成 `oh-my-sage-mcp`,启动更快,也不依赖网络。 ### HTTP(Streamable HTTP 客户端) diff --git a/deploy/install-local.ps1 b/deploy/install-local.ps1 index af7cc9a..b09ce0e 100644 --- a/deploy/install-local.ps1 +++ b/deploy/install-local.ps1 @@ -4,11 +4,15 @@ .DESCRIPTION 注册一个当前用户登录时启动的计划任务,后台无窗口运行(无需管理员权限): - node <仓库>/dist/mcp/mcp/index.js --http + node <安装目录>/dist/mcp/mcp/index.js --http + 安装目录是 npm 全局安装的 oh-my-sage-mcp 包,或者自己构建的仓库目录。 进程退出后一分钟内自动重新拉起。网关登录一次后,客户端重启无需重新输入登录码。 配置(GATEWAY_URL、MCP_AUTH_TOKEN 等)写入 %LOCALAPPDATA%\oh-my-sage\.env, 由 node --env-file 读取(需要 Node.js 20.6+)。 +.EXAMPLE + npm install -g oh-my-sage-mcp + pwsh "$(npm root -g)/oh-my-sage-mcp/deploy/install-local.ps1" -GatewayUrl http://192.168.0.5 .EXAMPLE npm run build:mcp pwsh deploy/install-local.ps1 -GatewayUrl http://192.168.0.5 @@ -51,7 +55,7 @@ if ($Uninstall) { # ==================== 前置检查 ==================== $repo = Split-Path -Parent $PSScriptRoot $entry = Join-Path $repo 'dist\mcp\mcp\index.js' -if (-not (Test-Path -LiteralPath $entry)) { throw "未找到 $entry,请先在仓库根目录执行 npm run build:mcp" } +if (-not (Test-Path -LiteralPath $entry)) { throw "未找到 $entry。从仓库安装时请先在仓库根目录执行 npm run build:mcp;也可以 npm install -g oh-my-sage-mcp 后运行包里的这个脚本" } $node = (Get-Command node -ErrorAction Stop).Source $nodeVersion = [version]((& $node -v).TrimStart('v')) if ($nodeVersion -lt [version]'20.6.0') { throw "需要 Node.js 20.6 或更高版本(当前 $nodeVersion)" } diff --git a/deploy/install-local.sh b/deploy/install-local.sh index ff70ac8..6080b8f 100644 --- a/deploy/install-local.sh +++ b/deploy/install-local.sh @@ -3,8 +3,8 @@ # macOS: launchd LaunchAgent(登录时启动,退出后自动重启) # Linux: systemd --user 服务(Restart=on-failure) # -# 用法(先在仓库根目录 npm run build:mcp): -# deploy/install-local.sh [-g 网关地址] [-p 端口] [-t token] [-n 服务名] +# 用法(npm install -g oh-my-sage-mcp 后运行包里的这个脚本,或在仓库根目录先 npm run build:mcp): +# bash "$(npm root -g)/oh-my-sage-mcp/deploy/install-local.sh" [-g 网关地址] [-p 端口] [-t token] [-n 服务名] # deploy/install-local.sh -u # 卸载 set -euo pipefail @@ -48,7 +48,7 @@ if [ "$UNINSTALL" = 1 ]; then fi # ==================== 前置检查 ==================== -[ -f "$ENTRY" ] || { echo "未找到 $ENTRY,请先执行 npm run build:mcp" >&2; exit 1; } +[ -f "$ENTRY" ] || { echo "未找到 $ENTRY。从仓库安装时请先执行 npm run build:mcp;也可以 npm install -g oh-my-sage-mcp 后运行包里的这个脚本" >&2; exit 1; } NODE="$(command -v node)" || { echo "未找到 node" >&2; exit 1; } [ -n "$GATEWAY_URL" ] || echo "提示:未设置 -g 网关地址,首次调用 mijia_auth 时需要传 gateway_url" >&2 diff --git a/docs/images/install.webp b/docs/images/install.webp index e7f3e18..a1b297d 100644 Binary files a/docs/images/install.webp and b/docs/images/install.webp differ diff --git a/package-lock.json b/package-lock.json index a975b6a..c5bdeb1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "oh-my-sage", - "version": "0.0.2", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "oh-my-sage", - "version": "0.0.2", + "version": "0.1.0", "dependencies": { "@ai-sdk/anthropic": "^0.0.51", "@ai-sdk/openai": "^0.0.58", diff --git a/package.json b/package.json index c6f516c..cae468e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "oh-my-sage", - "version": "0.0.2", + "version": "0.1.0", + "private": true, "scripts": { "dev": "next dev", @@ -9,7 +10,8 @@ "start": "next start", "lint": "next lint", "test": "npx tsx src/test.ts", - "test:unit": "tsx --test tests/**/*.test.ts" + "test:unit": "tsx --test tests/**/*.test.ts", + "build:npm": "npm run build:mcp && node scripts/build-npm-package.mjs" }, "bin": { "oh-my-sage-mcp": "./dist/mcp/mcp/index.js" diff --git a/scripts/build-npm-package.mjs b/scripts/build-npm-package.mjs new file mode 100644 index 0000000..d00a0df --- /dev/null +++ b/scripts/build-npm-package.mjs @@ -0,0 +1,86 @@ +#!/usr/bin/env node +/** + * 组装发布到 npm 的 oh-my-sage-mcp 包。 + * + * 根 package.json 是网页版(Next.js / antd 等),不能直接发布。本脚本在 dist/npm/ + * 下生成一个只含 MCP Server 的独立包: + * - package.json:名称 oh-my-sage-mcp,版本取根 package.json,依赖只含编译产物实际引用的包 + * - dist/mcp/:MCP 编译产物(不含 source map,源码不随包发布) + * - deploy/:本机常驻安装脚本 + * - README.md:根 README,图片改为 GitHub 绝对地址(npm 页面无法解析相对路径) + * - LICENSE + * + * 用法:npm run build:mcp && node scripts/build-npm-package.mjs + * 发布:npm publish dist/npm --access public + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; + +const root = process.cwd(); +const out = path.join(root, 'dist', 'npm'); +const mcpDist = path.join(root, 'dist', 'mcp'); +const rootPkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); + +if (!fs.existsSync(path.join(mcpDist, 'mcp', 'index.js'))) { + console.error('未找到 dist/mcp/mcp/index.js,请先执行 npm run build:mcp'); + process.exit(1); +} + +fs.rmSync(out, { recursive: true, force: true }); +fs.mkdirSync(out, { recursive: true }); + +// ==================== 依赖:复用 Docker 镜像的最小依赖扫描 ==================== + +const runtimePkgPath = path.join(out, '.runtime-package.json'); +execFileSync(process.execPath, ['deploy/mcp-runtime-package.mjs', 'package.json', 'dist/mcp', runtimePkgPath], { stdio: 'inherit' }); +const { dependencies } = JSON.parse(fs.readFileSync(runtimePkgPath, 'utf8')); +fs.rmSync(runtimePkgPath); + +// ==================== 编译产物 ==================== + +fs.cpSync(mcpDist, path.join(out, 'dist', 'mcp'), { + recursive: true, + filter: (source) => !source.endsWith('.map'), +}); + +// ==================== 本机常驻安装脚本 ==================== +// 脚本按自身位置找 ../dist/mcp/mcp/index.js,随包发布后全局安装即可直接使用,无需克隆仓库 + +fs.mkdirSync(path.join(out, 'deploy'), { recursive: true }); +for (const name of ['install-local.ps1', 'install-local.sh']) { + fs.copyFileSync(path.join(root, 'deploy', name), path.join(out, 'deploy', name)); +} + +// ==================== package.json ==================== + +const repoUrl = 'https://github.com/allocnode/oh-my-sage'; +const pkg = { + name: 'oh-my-sage-mcp', + version: rootPkg.version, + description: '米家自动化极客版 MCP Server:在任意 AI Agent 里用说话的方式创建和修改米家中枢网关的自动化规则', + keywords: ['mcp', 'mcp-server', 'model-context-protocol', 'mijia', 'xiaomi', 'smart-home', '米家', '极客版', '中枢网关'], + homepage: `${repoUrl}#readme`, + bugs: { url: `${repoUrl}/issues` }, + repository: { type: 'git', url: `git+${repoUrl}.git` }, + license: 'MIT', + bin: { 'oh-my-sage-mcp': 'dist/mcp/mcp/index.js' }, + main: 'dist/mcp/mcp/index.js', + types: 'dist/mcp/mcp/index.d.ts', + files: ['dist', 'deploy'], + engines: { node: '>=20' }, + dependencies, +}; +fs.writeFileSync(path.join(out, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`); + +// ==================== README 与 LICENSE ==================== + +const rawBase = 'https://raw.githubusercontent.com/allocnode/oh-my-sage/main/'; +const readme = fs.readFileSync(path.join(root, 'README.md'), 'utf8') + .replace(/(\]\(|src=")(docs\/images\/)/g, `$1${rawBase}$2`) + .replace(/\]\((?!https?:|#|mailto:)([^)]+)\)/g, `](${repoUrl}/blob/main/$1)`); +fs.writeFileSync(path.join(out, 'README.md'), readme); +fs.copyFileSync(path.join(root, 'LICENSE'), path.join(out, 'LICENSE')); + +console.log(`已生成 ${path.relative(root, out)}:${pkg.name}@${pkg.version},依赖 ${Object.keys(dependencies).join(', ')}`); diff --git a/scripts/smoke-npm-package.mjs b/scripts/smoke-npm-package.mjs new file mode 100644 index 0000000..11c4b93 --- /dev/null +++ b/scripts/smoke-npm-package.mjs @@ -0,0 +1,59 @@ +// Smoke test for the packed oh-my-sage-mcp: stdio handshake + tool list, then HTTP /healthz + MCP initialize. +// Runs against the installed package in the current directory; never connects to a gateway. +import { spawn } from 'node:child_process'; +import { createRequire } from 'node:module'; +import path from 'node:path'; + +const require = createRequire(path.join(process.cwd(), 'x.js')); +const entry = require.resolve('oh-my-sage-mcp/dist/mcp/mcp/index.js'); +const fail = (msg) => { console.error('FAIL', msg); process.exit(1); }; + +// ---------- stdio ---------- +const child = spawn(process.execPath, [entry], { env: { ...process.env, GATEWAY_URL: 'http://192.0.2.1' }, stdio: ['pipe', 'pipe', 'pipe'] }); +let buf = ''; +const pending = new Map(); +child.stdout.on('data', (d) => { + buf += d; + let i; + while ((i = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, i); buf = buf.slice(i + 1); + if (!line.trim()) continue; + const msg = JSON.parse(line); + pending.get(msg.id)?.(msg); + } +}); +const rpc = (id, method, params) => new Promise((resolve, reject) => { + pending.set(id, resolve); + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n'); + setTimeout(() => reject(new Error('timeout ' + method)), 15000); +}); +const init = await rpc(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'smoke', version: '0' } }); +child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n'); +const tools = await rpc(2, 'tools/list', {}); +const status = await rpc(3, 'tools/call', { name: 'mijia_status', arguments: {} }); +child.kill(); +const names = tools.result.tools.map((t) => t.name); +console.log('stdio server', init.result.serverInfo, 'tools', names.length); +if (init.result.serverInfo.version !== process.argv[2]) fail('version mismatch'); +if (names.length !== 32) fail('expected 32 tools'); +console.log('mijia_status', JSON.stringify(status.result.content?.[0]?.text ?? status.result).slice(0, 120)); + +// ---------- http ---------- +const port = 38790; +const srv = spawn(process.execPath, [entry, '--http'], { env: { ...process.env, MCP_HTTP_PORT: String(port) }, stdio: ['ignore', 'pipe', 'pipe'] }); +let ok = false; +for (let i = 0; i < 40 && !ok; i++) { + await new Promise((r) => setTimeout(r, 250)); + try { const r = await fetch(`http://127.0.0.1:${port}/healthz`); ok = r.ok; if (ok) console.log('healthz', await r.text()); } catch {} +} +if (!ok) { srv.kill(); fail('healthz'); } +const r = await fetch(`http://127.0.0.1:${port}/mcp`, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'smoke', version: '0' } } }), +}); +const body = await r.text(); +srv.kill(); +if (!r.ok || !body.includes('oh-my-sage')) fail('http initialize ' + r.status + ' ' + body.slice(0, 200)); +console.log('http initialize', r.status, 'session', r.headers.get('mcp-session-id') ? 'yes' : 'no'); +console.log('ALL OK'); diff --git a/src/mcp/index.ts b/src/mcp/index.ts index 3537c91..6829c44 100644 --- a/src/mcp/index.ts +++ b/src/mcp/index.ts @@ -9,7 +9,22 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { getConfig, type Config } from "./config.js"; import { resolveHttpOptions, startHttpServer } from "./http.js"; -import { createServer } from "./server.js"; +import { createServer, SERVER_VERSION } from "./server.js"; + +const HELP = `oh-my-sage-mcp ${SERVER_VERSION} +米家自动化极客版 MCP Server + +用法: + oh-my-sage-mcp 以 stdio 方式运行(由 AI Agent 启动) + oh-my-sage-mcp --http 以 Streamable HTTP 方式运行,地址 http://127.0.0.1:3790/mcp + oh-my-sage-mcp --version 显示版本号 + oh-my-sage-mcp --help 显示本帮助 + +环境变量: + GATEWAY_URL 米家中枢网关地址,例如 http://192.168.0.5 + MCP_HTTP_HOST / MCP_HTTP_PORT / MCP_AUTH_TOKEN / MCP_ALLOWED_HOSTS HTTP 模式参数 + +文档:https://github.com/allocnode/oh-my-sage`; function isHttpTransport(): boolean { return process.argv.slice(2).includes("--http") || (process.env.MCP_TRANSPORT || "").toLowerCase() === "http"; @@ -19,6 +34,16 @@ function isHttpTransport(): boolean { * 启动 MCP Server */ async function main(): Promise { + const args = process.argv.slice(2); + if (args.includes("--version") || args.includes("-v")) { + console.log(SERVER_VERSION); + return; + } + if (args.includes("--help") || args.includes("-h")) { + console.log(HELP); + return; + } + // 支持从环境变量读取配置 const userConfig: Config | undefined = process.env.GATEWAY_URL ? { gatewayUrl: process.env.GATEWAY_URL } diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 8ef5689..3d0da7f 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -5,6 +5,8 @@ * 但所有实例共享同一个 GatewayManager 与 GraphDraftStore。 */ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { createGatewayManager } from "../core/index.js"; import type { GatewayManager } from "../core/gateway/manager.js"; @@ -19,7 +21,25 @@ import { } from "./tools/index.js"; export const SERVER_NAME = "oh-my-sage"; -export const SERVER_VERSION = "1.0.0"; +export const SERVER_VERSION = readPackageVersion(); + +/** + * 读取 package.json 中的版本号 + * + * 编译产物位于 dist/mcp/mcp/,仓库与 npm 包里 package.json 都在其上三级; + * 用 tsx 直接运行源码时位于 src/mcp/,在上两级。 + */ +function readPackageVersion(): string { + for (const relative of ["../../..", "../.."]) { + try { + const pkg = JSON.parse(readFileSync(join(__dirname, relative, "package.json"), "utf8")) as { name?: string; version?: string }; + if (pkg.name?.startsWith("oh-my-sage") && pkg.version) return pkg.version; + } catch { + // 该位置没有 package.json,继续尝试下一个 + } + } + return "0.0.0"; +} /** * 创建并配置 MCP Server