diff --git a/external_plugins/gitea/.claude-plugin/plugin.json b/external_plugins/gitea/.claude-plugin/plugin.json new file mode 100644 index 00000000..f7afd8a6 --- /dev/null +++ b/external_plugins/gitea/.claude-plugin/plugin.json @@ -0,0 +1,29 @@ +{ + "name": "gitea", + "version": "0.2.0", + "description": "Gitea integration with compact, context-friendly MCP output: token auth plus issues, pull requests, repositories, labels, milestones, releases, organizations and Gitea Actions through the Gitea REST API, including self-hosted instances.", + "description_i18n": { + "en": "Gitea integration with compact, context-friendly MCP output: token auth plus issues, pull requests, repositories, labels, milestones, releases, organizations and Gitea Actions through the Gitea REST API, including self-hosted instances.", + "zh-CN": "Gitea 集成,MCP 输出精简、节省上下文:基于令牌认证,通过 Gitea REST API 管理 Issue、Pull Request、仓库、标签、里程碑、Release、组织与 Gitea Actions,支持自托管实例。" + }, + "author": { + "name": "Lloyd Culpepper", + "url": "https://github.com/OPVL" + }, + "homepage": "https://github.com/OPVL/gitea-mcp", + "repository": "https://github.com/OPVL/gitea-mcp", + "license": "Apache-2.0", + "keywords": [ + "git", + "gitea", + "issues", + "pull-request", + "repository", + "releases", + "actions", + "self-hosted", + "mcp" + ], + "skills": "./skills", + "mcpServers": "./.mcp.json" +} diff --git a/external_plugins/gitea/.mcp.json b/external_plugins/gitea/.mcp.json new file mode 100644 index 00000000..cb775ac0 --- /dev/null +++ b/external_plugins/gitea/.mcp.json @@ -0,0 +1,10 @@ +{ + "mcpServers": { + "gitea": { + "type": "stdio", + "command": "sh", + "args": ["${CLAUDE_PLUGIN_ROOT}/mcp/run-node.sh", "${CLAUDE_PLUGIN_ROOT}/mcp/server.mjs"], + "timeoutMs": 30000 + } + } +} diff --git a/external_plugins/gitea/.zcode-plugin/plugin.json b/external_plugins/gitea/.zcode-plugin/plugin.json new file mode 100644 index 00000000..f7afd8a6 --- /dev/null +++ b/external_plugins/gitea/.zcode-plugin/plugin.json @@ -0,0 +1,29 @@ +{ + "name": "gitea", + "version": "0.2.0", + "description": "Gitea integration with compact, context-friendly MCP output: token auth plus issues, pull requests, repositories, labels, milestones, releases, organizations and Gitea Actions through the Gitea REST API, including self-hosted instances.", + "description_i18n": { + "en": "Gitea integration with compact, context-friendly MCP output: token auth plus issues, pull requests, repositories, labels, milestones, releases, organizations and Gitea Actions through the Gitea REST API, including self-hosted instances.", + "zh-CN": "Gitea 集成,MCP 输出精简、节省上下文:基于令牌认证,通过 Gitea REST API 管理 Issue、Pull Request、仓库、标签、里程碑、Release、组织与 Gitea Actions,支持自托管实例。" + }, + "author": { + "name": "Lloyd Culpepper", + "url": "https://github.com/OPVL" + }, + "homepage": "https://github.com/OPVL/gitea-mcp", + "repository": "https://github.com/OPVL/gitea-mcp", + "license": "Apache-2.0", + "keywords": [ + "git", + "gitea", + "issues", + "pull-request", + "repository", + "releases", + "actions", + "self-hosted", + "mcp" + ], + "skills": "./skills", + "mcpServers": "./.mcp.json" +} diff --git a/external_plugins/gitea/LICENSE b/external_plugins/gitea/LICENSE new file mode 100644 index 00000000..57bc88a1 --- /dev/null +++ b/external_plugins/gitea/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/external_plugins/gitea/README.md b/external_plugins/gitea/README.md new file mode 100644 index 00000000..fc061de8 --- /dev/null +++ b/external_plugins/gitea/README.md @@ -0,0 +1,106 @@ +# Gitea + +[中文文档](./README_CN.md) + +Gitea integration for ZCode: token-based authentication plus issue, +pull-request, repository, label, milestone, release, organization, and +Gitea Actions management, all through the Gitea REST API (`/api/v1`). +Works with gitea.com and self-hosted instances. + +Mirrors the coverage of the GitHub plugin where Gitea has equivalents (no +Codespaces or gists, which Gitea does not have in core). + +## Components + +- **MCP server** (`mcp/server.mjs`): a zero-dependency Node.js (≥ 18) stdio + server with 33 tools. `mcp/run-node.sh` finds a Node runtime even when ZCode + Desktop starts without your shell `PATH` (it checks `PATH`, then nvm, then + Homebrew and system locations). It is a POSIX shell script, so macOS and + Linux are supported. +- **Skills**: `setup`, `issue`, `pr`, `repo`, `release`, `actions`. + +## Requirements + +- Node.js 18 or newer. +- A Gitea instance and an API token for it. + +## Configuration + +No secrets are stored in the plugin. Environment variables take precedence +over the config file: + +| Source | Keys | +|---|---| +| Environment | `GITEA_URL`, `GITEA_TOKEN` (optionally `GITEA_MCP_CONFIG`) | +| Config file | `~/.config/gitea/mcp.json` → `{"url": "...", "token": "..."}` (0600) | + +Create a scoped token in Gitea under **Settings → Applications → Access +Tokens**: `read:user`, `read/write:repository`, `read/write:issue`, +`read:organization` (add `write:organization` to create organization +repositories), and optionally `read:misc` for the instance version. + +The `setup` skill walks through this and verifies it with the `whoami` tool. + +Scope traps: + +- A token with only `write:repository` (typical for git push automation) + **cannot read issues**. A 403 there is a scope problem, not a permission + problem. +- Scopes are fixed per token; regenerating a token never widens an old one. + +## Tools + +whoami; list_repos, search_repos, get_repo, create_repo, edit_repo, +delete_repo (confirm-gated), list_branches, list_tags; list_issues, +search_issues, get_issue (+recent comments), create_issue, edit_issue +(close/reopen), add_comment; list_labels, create_label, set_issue_labels +(replaces the set); list_milestones, create_milestone, edit_milestone; +list_prs, get_pr (+status checks, optional diff), create_pr, edit_pr, +merge_pr (merge/rebase/rebase-merge/squash/ff-only); list_releases, +create_release; list_orgs; list_action_runs, dispatch_workflow, +list_secrets, set_secret. + +## Compact output + +Raw Gitea responses are large: a single pull request embeds two complete +repository objects, and every user object carries avatars and profile +fields. Each tool maps the response to the fields an agent needs: + +- **Lists** print one line of `{page,count,more,total}` followed by one compact + JSON row per item. Rows contain no bodies. `page` and `limit` (≤ 50) control + paging. +- **Create and edit** tools return only the number or id, title, state and + URL. +- **`get_issue`** returns the issue and its 20 most recent comments + (`last_comments` changes this). Bodies are clipped at 6000 characters and + comments at 1500; `full: true` returns them unclipped. +- **`get_pr`** includes mergeability, change stats and the head commit's + status checks. `include_diff: true` appends the raw diff, clipped at + `max_diff_chars` (default 20000). + +Measured against a real instance, `create_pr` output dropped from about 12,000 +characters to about 200, and a 20-item `list_issues` from over 60,000 +(previously truncated) to about 3,700. + +## Network access and side effects + +- **Network**: the MCP server makes HTTPS requests only to the Gitea URL you + configure. It contacts no other service and collects no telemetry. +- **Files read**: `~/.config/gitea/mcp.json` (or the `GITEA_MCP_CONFIG` path). + The plugin writes no files; the `setup` skill gives you commands to create + that file in your own terminal, so the token never passes through the + conversation. +- **Commands**: `run-node.sh` starts Node.js. Skills may run read-only `git` + commands such as `git remote get-url origin` to work out the repository. +- **Writes to Gitea**: create/edit/merge/delete tools change data on your + instance. The skills tell the agent to confirm with you before every write. + `delete_repo` additionally requires `confirm: true`. +- **Secrets**: `set_secret` values pass through the conversation and tool + logs; use the Gitea web UI for high-value secrets. `list_secrets` returns + names only. +- No hooks are installed. + +## License + +Apache-2.0. See [LICENSE](./LICENSE). No third-party code or assets are +bundled. diff --git a/external_plugins/gitea/README_CN.md b/external_plugins/gitea/README_CN.md new file mode 100644 index 00000000..ea423d19 --- /dev/null +++ b/external_plugins/gitea/README_CN.md @@ -0,0 +1,94 @@ +# Gitea + +[English](./README.md) + +ZCode 的 Gitea 集成:基于令牌认证,通过 Gitea REST API(`/api/v1`)管理 +Issue、Pull Request、仓库、标签、里程碑、Release、组织和 Gitea Actions。 +同时支持 gitea.com 与自托管实例。 + +在 Gitea 有对应功能的范围内,覆盖面与 GitHub 插件一致(Gitea 核心不提供 +Codespaces 和 Gist,因此不包含这两项)。 + +## 组成 + +- **MCP 服务器**(`mcp/server.mjs`):零依赖的 Node.js(≥ 18)stdio 服务器, + 共 33 个工具。即使 ZCode Desktop 启动时没有继承 shell 的 `PATH`, + `mcp/run-node.sh` 也能找到 Node 运行时(依次检查 `PATH`、nvm、Homebrew + 与系统目录)。该脚本为 POSIX shell 脚本,支持 macOS 和 Linux。 +- **Skills**:`setup`、`issue`、`pr`、`repo`、`release`、`actions`。 + +## 环境要求 + +- Node.js 18 或更高版本。 +- 一个 Gitea 实例及其 API 令牌。 + +## 配置 + +插件本身不保存任何密钥。环境变量优先于配置文件: + +| 来源 | 键 | +|---|---| +| 环境变量 | `GITEA_URL`、`GITEA_TOKEN`(可选 `GITEA_MCP_CONFIG`) | +| 配置文件 | `~/.config/gitea/mcp.json` → `{"url": "...", "token": "..."}`(权限 0600) | + +在 Gitea 的 **设置 → 应用 → 访问令牌** 中创建限定权限的令牌:`read:user`、 +`read/write:repository`、`read/write:issue`、`read:organization`(创建组织 +仓库时还需 `write:organization`),可选 `read:misc` 用于读取实例版本。 + +`setup` skill 会引导完成上述配置,并用 `whoami` 工具验证。 + +常见权限陷阱: + +- 只有 `write:repository` 的令牌(常用于 git 推送自动化)**无法读取 Issue**。 + 这时出现的 403 是令牌权限范围问题,而不是仓库权限问题。 +- 令牌的权限范围在创建时固定,重新生成不会扩大旧令牌的范围。 + +## 工具 + +whoami;list_repos、search_repos、get_repo、create_repo、edit_repo、 +delete_repo(需确认)、list_branches、list_tags;list_issues、 +search_issues、get_issue(含最近评论)、create_issue、edit_issue +(关闭/重新打开)、add_comment;list_labels、create_label、 +set_issue_labels(整体替换);list_milestones、create_milestone、 +edit_milestone;list_prs、get_pr(含状态检查,可选 diff)、create_pr、 +edit_pr、merge_pr(merge/rebase/rebase-merge/squash/ff-only); +list_releases、create_release;list_orgs;list_action_runs、 +dispatch_workflow、list_secrets、set_secret。 + +## 精简输出 + +Gitea 的原始响应体积很大:一个 Pull Request 内嵌两个完整的仓库对象,每个 +用户对象都带有头像和资料字段。每个工具都会把响应映射为 Agent 真正需要的 +字段: + +- **列表**先输出一行 `{page,count,more,total}`,随后每项一行紧凑 JSON。 + 列表行不含正文。用 `page` 和 `limit`(≤ 50)分页。 +- **创建和编辑**类工具只返回编号或 id、标题、状态和 URL。 +- **`get_issue`** 返回 Issue 及最近 20 条评论(可用 `last_comments` 调整)。 + 正文截断为 6000 字符,评论截断为 1500 字符;`full: true` 返回完整内容。 +- **`get_pr`** 包含可合并状态、变更统计和 head 提交的状态检查。 + `include_diff: true` 会附加原始 diff,按 `max_diff_chars`(默认 20000) + 截断。 + +在真实实例上实测:`create_pr` 的输出从约 12,000 字符降到约 200 字符; +20 条的 `list_issues` 从超过 60,000 字符(此前会被截断)降到约 3,700 字符。 + +## 网络访问与副作用 + +- **网络**:MCP 服务器只向你配置的 Gitea URL 发送 HTTPS 请求,不连接其他 + 服务,也不收集遥测数据。 +- **读取的文件**:`~/.config/gitea/mcp.json`(或 `GITEA_MCP_CONFIG` 指定的 + 路径)。插件不写任何文件;`setup` skill 会给出命令,由你在自己的终端 + 中创建该文件,令牌不会经过对话。 +- **执行的命令**:`run-node.sh` 启动 Node.js。Skills 可能执行只读的 `git` + 命令(如 `git remote get-url origin`)来确定仓库。 +- **对 Gitea 的写操作**:创建、编辑、合并、删除类工具会修改实例上的数据。 + Skills 要求 Agent 在每次写操作前先征得你的确认;`delete_repo` 还必须 + 传入 `confirm: true`。 +- **密钥**:`set_secret` 的值会经过对话和工具日志;高价值密钥请在 Gitea + 网页界面中设置。`list_secrets` 只返回名称。 +- 不安装任何 hook。 + +## 许可证 + +Apache-2.0,见 [LICENSE](./LICENSE)。未捆绑任何第三方代码或资源。 diff --git a/external_plugins/gitea/mcp/run-node.sh b/external_plugins/gitea/mcp/run-node.sh new file mode 100755 index 00000000..4a9ca192 --- /dev/null +++ b/external_plugins/gitea/mcp/run-node.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Resolve a Node runtime (>= 18) for the gitea plugin's MCP server. +# ZCode Desktop may be launched without the user's shell PATH (no nvm), so +# try PATH first, then the newest nvm install, then common system locations. +if command -v node >/dev/null 2>&1; then + exec node "$@" +fi +node_bin=$(ls -1 "$HOME"/.nvm/versions/node/*/bin/node 2>/dev/null | sort -V | tail -n 1) +if [ -n "$node_bin" ]; then + exec "$node_bin" "$@" +fi +for cand in /opt/homebrew/bin/node /usr/local/bin/node /usr/bin/node; do + if [ -x "$cand" ]; then + exec "$cand" "$@" + fi +done +echo "gitea plugin: no Node runtime found (need Node >= 18 on PATH, nvm, or Homebrew)" >&2 +exit 127 diff --git a/external_plugins/gitea/mcp/server.mjs b/external_plugins/gitea/mcp/server.mjs new file mode 100644 index 00000000..5fca42f4 --- /dev/null +++ b/external_plugins/gitea/mcp/server.mjs @@ -0,0 +1,1269 @@ +#!/usr/bin/env node +/** + * Gitea MCP server (gitea plugin). + * + * Zero-dependency stdio JSON-RPC 2.0 server wrapping the Gitea REST API + * (/api/v1). Requires Node >= 18 (global fetch). + * + * Configuration is resolved per call, env over file: + * - GITEA_URL base URL of the Gitea instance (e.g. https://gitea.example.com) + * - GITEA_TOKEN API token with the required scopes + * - GITEA_MCP_CONFIG path to a JSON config file (default ~/.config/gitea/mcp.json) + * The config file is {"url": "...", "token": "..."} with 0600 permissions. + * + * Output is deliberately minimal (modelled on github-mcp-server's "minimal" + * types): raw Gitea objects embed full user and repository objects (a single + * PR carries two complete repos), so every tool maps the response through a + * shaper below, nulls/empties are pruned, JSON is compact, lists are one row + * per line, and long text (bodies, comments, diffs) is clipped with a marker. + */ +import { readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { createInterface } from "node:readline"; + +const SERVER_NAME = "gitea"; +const SERVER_VERSION = "0.2.0"; +const MAX_OUTPUT_CHARS = 40000; +const DEFAULT_LIMIT = 20; +const BODY_MAX = 6000; // issue / PR body in get_* (full=true lifts it) +const COMMENT_MAX = 1500; // per comment in get_issue (full=true lifts it) +const DEFAULT_COMMENTS = 20; // most recent comments returned by get_issue +const DIFF_MAX = 20000; // default diff cap for get_pr + +class ConfigError extends Error {} +class ApiError extends Error { + constructor(status, message) { + super(message); + this.status = status; + } +} + +// ---------------------------------------------------------------- config ---- + +async function loadConfig() { + let file = {}; + const path = + process.env.GITEA_MCP_CONFIG || + join(homedir(), ".config", "gitea", "mcp.json"); + try { + file = JSON.parse(await readFile(path, "utf8")); + } catch { + /* absent or invalid: env vars may still carry everything */ + } + const url = String(process.env.GITEA_URL || file.url || "") + .trim() + .replace(/\/+$/, ""); + const token = String(process.env.GITEA_TOKEN || file.token || "").trim(); + return { url, token, path }; +} + +const CONFIG_HELP = (cfg) => + `Gitea is not configured. Either set GITEA_URL and GITEA_TOKEN in the ` + + `environment, or create ${cfg.path} as {"url": "https://your-gitea", ` + + `"token": ""} with 0600 permissions. Mint a scoped token in ` + + `Gitea under Settings -> Applications -> Access Tokens, then run the ` + + `gitea setup skill or the whoami tool to verify.`; + +// ------------------------------------------------------------------ http ---- + +function splitRepo(repo) { + const m = /^([\w.\-]+)\/([\w.\-]+)$/.exec(String(repo || "").trim()); + if (!m) throw new Error(`Invalid repo "${repo}" — expected "owner/name".`); + return { owner: m[1], name: m[2] }; +} + +async function apiCall(cfg, method, path, { query, body, raw } = {}) { + if (!cfg.url || !cfg.token) throw new ConfigError(CONFIG_HELP(cfg)); + const url = new URL(cfg.url + path); + for (const [k, v] of Object.entries(query || {})) { + if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v)); + } + const headers = { + Authorization: `token ${cfg.token}`, + Accept: raw ? "application/vnd.gitea.raw" : "application/json", + }; + if (body !== undefined) headers["Content-Type"] = "application/json"; + let res; + try { + res = await fetch(url, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch (e) { + throw new Error(`Cannot reach ${cfg.url}: ${e.cause?.code || e.message}`); + } + const meta = { + scopes: res.headers.get("x-oauth-scopes"), + link: res.headers.get("link"), + total: res.headers.get("x-total-count"), + }; + if (!res.ok) { + let detail = ""; + try { + const j = await res.json(); + if (j && j.message) detail = j.message; + } catch { + /* non-JSON error body */ + } + let msg = `HTTP ${res.status}${detail ? `: ${detail}` : ` ${res.statusText}`}`; + if (res.status === 401) + msg += ` — the token was rejected. Check that it is valid and not expired (whoami shows the scopes the server sees).`; + if (res.status === 403) + msg += ` — the token may lack the required scope (e.g. read:issue / write:repository).`; + if (res.status === 404) + msg += ` — check owner/repo spelling, and that the token scope covers it. It may also be an endpoint your Gitea version does not expose.`; + throw new ApiError(res.status, msg); + } + if (res.status === 204) return { data: null, ...meta }; + if (raw) return { data: await res.text(), ...meta }; + return { data: await res.json(), ...meta }; +} + +// GET a list endpoint; unwraps the {data:[...]} / {workflow_runs:[...]} envelopes. +async function apiList(cfg, path, opts = {}) { + const r = await apiCall(cfg, "GET", path, opts); + const d = r.data; + let items = d; + if (!Array.isArray(d)) { + if (Array.isArray(d?.data)) items = d.data; + else if (Array.isArray(d?.workflow_runs)) items = d.workflow_runs; + else if (Array.isArray(d?.entries)) items = d.entries; + if (r.total == null && typeof d?.total_count === "number") r.total = d.total_count; + } + r.data = Array.isArray(items) ? items : []; + return r; +} + +// ---------------------------------------------------------------- helpers --- + +function isoDate(value) { + // Accept YYYY-MM-DD and pass through full ISO timestamps unchanged. + if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00:00Z`; + return value; +} + +function pageArgs(args) { + return { + limit: Math.min(Number(args.limit) || DEFAULT_LIMIT, 50), + page: Number(args.page) || 1, + }; +} + +// Drop null / undefined / "" / [] / {} recursively. false and 0 are kept. +function prune(v) { + if (Array.isArray(v)) { + const a = v.map(prune).filter((x) => x !== undefined); + return a.length ? a : undefined; + } + if (v && typeof v === "object") { + const o = {}; + for (const [k, x] of Object.entries(v)) { + const p = prune(x); + if (p !== undefined) o[k] = p; + } + return Object.keys(o).length ? o : undefined; + } + if (v === null || v === undefined || v === "") return undefined; + return v; +} + +const json = (v) => JSON.stringify(prune(v) ?? null); + +function cap(text) { + if (text.length > MAX_OUTPUT_CHARS) { + text = + text.slice(0, MAX_OUTPUT_CHARS) + + `\n…[truncated ${text.length - MAX_OUTPUT_CHARS} chars — narrow the query (labels, state, limit, page) and retry]`; + } + return text; +} + +function textResult(text) { + return { content: [{ type: "text", text: cap(text) }] }; +} + +// Single object or plain message → compact JSON / text. +function ok(value) { + return textResult(typeof value === "string" ? value : json(value)); +} + +// Paged list → meta line, then one compact JSON row per item. +function okList(rows, q, r) { + const more = r.link ? /rel="next"/.test(r.link) : rows.length >= q.limit; + const meta = json({ + page: q.page, + count: rows.length, + more, + total: r.total != null && r.total !== "" ? Number(r.total) : undefined, + }); + return textResult([meta, ...rows.map(json)].join("\n")); +} + +function clip(s, n) { + if (s === null || s === undefined) return undefined; + s = String(s); + if (!Number.isFinite(n) || s.length <= n) return s; + return s.slice(0, n) + `…[+${s.length - n} chars]`; +} + +const login = (u) => u?.login || u?.username || undefined; +const logins = (arr) => (arr || []).map(login).filter(Boolean); +const names = (arr) => (arr || []).map((x) => (typeof x === "string" ? x : x?.name)).filter(Boolean); +const day = (s) => (s ? String(s).slice(0, 10) : undefined); +const sha10 = (s) => (s ? String(s).slice(0, 10) : undefined); +const firstLine = (s, n) => (s ? clip(String(s).split("\n")[0].trim(), n) : undefined); +const nz = (n) => (n ? n : undefined); // drop zero counters + +function duration(start, end) { + const ms = Date.parse(end) - Date.parse(start); + if (!Number.isFinite(ms) || ms < 0) return undefined; + const s = Math.round(ms / 1000); + return s >= 60 ? `${Math.floor(s / 60)}m${s % 60}s` : `${s}s`; +} + +// ---------------------------------------------------------------- shapers --- +// Each shaper keeps only what an agent needs to reason or report; the raw +// objects are 10–50x larger (avatars, emails, nested repos, API URLs, ...). + +function repoRow(r) { + return { + full_name: r.full_name, + description: clip(r.description, 120), + private: r.private, + fork: r.fork || undefined, + archived: r.archived || undefined, + default_branch: r.default_branch, + stars: nz(r.stars_count), + open_issues: nz(r.open_issues_count), + updated: day(r.updated_at), + }; +} + +function repoPerm(p) { + if (!p) return undefined; + return p.admin ? "admin" : p.push ? "write" : p.pull ? "read" : "none"; +} + +function repoDetail(r) { + return { + full_name: r.full_name, + description: r.description, + url: r.html_url, + clone_url: r.clone_url, + ssh_url: r.ssh_url, + private: r.private, + fork: r.fork || undefined, + parent: r.parent?.full_name, + mirror: r.mirror || undefined, + template: r.template || undefined, + archived: r.archived, + default_branch: r.default_branch, + website: r.website, + permission: repoPerm(r.permissions), + size_kb: r.size, + stars: r.stars_count, + forks: r.forks_count, + watchers: r.watchers_count, + open_issues: r.open_issues_count, + open_prs: r.open_pr_counter, + releases: r.release_counter, + has_issues: r.has_issues, + has_pull_requests: r.has_pull_requests, + has_wiki: r.has_wiki, + has_actions: r.has_actions, + created: day(r.created_at), + updated: r.updated_at, + }; +} + +function repoRef(r) { + return { + full_name: r.full_name, + url: r.html_url, + private: r.private, + archived: r.archived || undefined, + default_branch: r.default_branch, + description: clip(r.description, 120), + }; +} + +function issueRow(i, withRepo = false) { + return { + repo: withRepo ? i.repository?.full_name : undefined, + number: i.number, + title: i.title, + state: i.pull_request ? (i.pull_request.merged ? "merged" : i.state) : i.state, + pr: i.pull_request ? true : undefined, + author: login(i.user), + labels: names(i.labels), + assignees: logins(i.assignees), + milestone: i.milestone?.title, + comments: nz(i.comments), + updated: day(i.updated_at), + }; +} + +function issueDetail(i, bodyMax) { + return { + ...issueRow(i), + url: i.html_url, + milestone: i.milestone ? `${i.milestone.title} (id ${i.milestone.id})` : undefined, + created: i.created_at, + updated: i.updated_at, + closed: i.closed_at, + due: day(i.due_date), + ref: i.ref, + locked: i.is_locked || undefined, + body: clip(i.body, bodyMax), + }; +} + +function issueRef(i) { + return { + number: i.number, + title: i.title, + state: i.state, + url: i.html_url, + labels: names(i.labels), + assignees: logins(i.assignees), + milestone: i.milestone?.title, + }; +} + +function commentRow(c, max) { + return { + id: c.id, + author: login(c.user), + at: c.created_at, + edited: c.updated_at && c.updated_at !== c.created_at ? true : undefined, + body: clip(c.body, max), + }; +} + +// head as "branch" for same-repo PRs, "owner:branch" when it comes from a fork. +// After the head branch is deleted Gitea reports ref "refs/pull/N/head"; the +// label still carries the original branch name. +function prHead(p) { + const h = p.head || {}; + const branch = h.ref && !h.ref.startsWith("refs/pull/") ? h.ref : h.label || h.ref; + const hr = h.repo?.full_name; + const br = p.base?.repo?.full_name; + if (hr && br && hr !== br && branch && !branch.includes(":")) return `${hr.split("/")[0]}:${branch}`; + return branch; +} + +function prState(p) { + return p.merged ? "merged" : p.state; +} + +function prRow(p) { + return { + number: p.number, + title: p.title, + state: prState(p), + draft: p.draft || undefined, + author: login(p.user), + head: prHead(p), + base: p.base?.ref, + labels: names(p.labels), + reviewers: logins(p.requested_reviewers), + comments: nz(p.comments), + updated: day(p.updated_at), + }; +} + +function prDetail(p, bodyMax) { + const open = p.state === "open" && !p.merged; + return { + ...prRow(p), + url: p.html_url, + head_sha: sha10(p.head?.sha), + mergeable: open ? p.mergeable : undefined, + merged_at: p.merged_at, + merged_by: login(p.merged_by), + merge_commit: sha10(p.merge_commit_sha), + assignees: logins(p.assignees), + milestone: p.milestone?.title, + review_comments: nz(p.review_comments), + changed_files: p.changed_files, + additions: p.additions, + deletions: p.deletions, + created: p.created_at, + updated: p.updated_at, + closed: p.closed_at, + body: clip(p.body, bodyMax), + }; +} + +function prRef(p) { + return { + number: p.number, + title: p.title, + state: prState(p), + head: prHead(p), + base: p.base?.ref, + url: p.html_url, + }; +} + +function branchRow(b) { + return { + name: b.name, + sha: sha10(b.commit?.id), + protected: b.protected || undefined, + date: day(b.commit?.timestamp), + msg: firstLine(b.commit?.message, 72), + }; +} + +function tagRow(t) { + return { + name: t.name, + sha: sha10(t.commit?.sha || t.id), + msg: firstLine(t.message, 72), + }; +} + +function labelRow(l) { + return { + id: l.id, + name: l.name, + color: l.color, + description: clip(l.description, 100), + exclusive: l.exclusive || undefined, + archived: l.is_archived || undefined, + }; +} + +function milestoneRow(m) { + return { + id: m.id, + title: m.title, + state: m.state, + open: m.open_issues, + closed: m.closed_issues, + due: day(m.due_on), + description: clip(m.description, 100), + }; +} + +function releaseRow(r) { + return { + id: r.id, + tag: r.tag_name, + name: r.name && r.name !== r.tag_name ? r.name : undefined, + draft: r.draft || undefined, + prerelease: r.prerelease || undefined, + published: day(r.published_at || r.created_at), + author: login(r.author), + assets: nz(r.assets?.length), + url: r.html_url, + }; +} + +function orgRow(o) { + return { + name: o.username || o.name, + full_name: o.full_name && o.full_name !== (o.username || o.name) ? o.full_name : undefined, + visibility: o.visibility, + description: clip(o.description, 100), + }; +} + +function taskRow(t) { + const done = !["running", "waiting", "pending", "blocked"].includes(t.status); + return { + id: t.id, + run: t.run_number, + workflow: t.workflow_id || t.name, + title: clip(t.display_title, 80), + event: t.event, + status: t.status, + branch: t.head_branch, + sha: sha10(t.head_sha), + started: t.run_started_at || t.created_at, + duration: done ? duration(t.run_started_at, t.updated_at) : undefined, + url: t.status === "failure" ? t.url : undefined, + }; +} + +// ------------------------------------------------------------------ tools --- + +const TOOLS = [ + // ---- identity ---- + { + name: "whoami", + description: + "Verify Gitea authentication and configuration. Returns the authenticated user, the scopes the server reports for the token (X-oauth-scopes), and the instance version. Run this first in any session and after changing tokens.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + run: async (a, cfg) => { + const me = await apiCall(cfg, "GET", "/api/v1/user"); + let version = null; + try { + version = (await apiCall(cfg, "GET", "/api/v1/version")).data?.version ?? null; + } catch { + /* version endpoint unavailable on some configs */ + } + return ok({ + user: me.data.login, + full_name: me.data.full_name, + is_admin: me.data.is_admin ?? undefined, + token_scopes: (me.scopes || "").split(",").map((s) => s.trim()).filter(Boolean), + instance_version: version, + url: cfg.url, + }); + }, + }, + + // ---- repositories ---- + { + name: "list_repos", + description: + "List repositories: your own (target=mine), an organization's (target=org + org), or another user's (target=user + username). Returns one compact row per repo.", + inputSchema: { + type: "object", + properties: { + target: { type: "string", enum: ["mine", "org", "user"], default: "mine" }, + org: { type: "string", description: "Organization name (target=org)" }, + username: { type: "string", description: "User name (target=user)" }, + ...paged(), + }, + }, + run: async (a, cfg) => { + const q = pageArgs(a); + let path; + if (a.target === "org") { + if (!a.org) throw new Error("target=org requires 'org'."); + path = `/api/v1/orgs/${a.org}/repos`; + } else if (a.target === "user") { + if (!a.username) throw new Error("target=user requires 'username'."); + path = `/api/v1/users/${a.username}/repos`; + } else { + path = "/api/v1/user/repos"; + } + const r = await apiList(cfg, path, { query: q }); + return okList(r.data.map(repoRow), q, r); + }, + }, + { + name: "search_repos", + description: "Search repositories by keyword across the instance.", + inputSchema: { + type: "object", + properties: { q: { type: "string" }, ...paged() }, + }, + run: async (a, cfg) => { + const q = pageArgs(a); + const r = await apiList(cfg, "/api/v1/repos/search", { query: { q: a.q, ...q } }); + return okList(r.data.map(repoRow), q, r); + }, + }, + { + name: "get_repo", + description: + "Get one repository's details: description, visibility, default branch, your permission level, clone URLs, size and counters.", + inputSchema: repoParams({}), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const r = await apiCall(cfg, "GET", `/api/v1/repos/${owner}/${name}`); + return ok(repoDetail(r.data)); + }, + }, + { + name: "create_repo", + description: + "Create a repository under your account (omit org) or an organization (set org). Requires write:repository (org repos: write:organization). Returns the new repo's name and URL.", + inputSchema: { + type: "object", + properties: { + name: { type: "string" }, + org: { type: "string", description: "Create inside this organization instead of your account" }, + description: { type: "string" }, + private: { type: "boolean", default: true }, + default_branch: { type: "string", default: "main" }, + auto_init: { type: "boolean", default: false, description: "Initialize with a README commit" }, + license: { type: "string", description: "SPDX id, e.g. MIT (only with auto_init)" }, + gitignores: { type: "string", description: "Comma-separated template names (only with auto_init)" }, + }, + }, + run: async (a, cfg) => { + const body = pick(a, ["name", "description", "private", "default_branch", "auto_init", "license", "gitignores"]); + body.private = a.private !== false; + body.default_branch = a.default_branch || "main"; + const path = a.org ? `/api/v1/orgs/${a.org}/repos` : "/api/v1/user/repos"; + const r = await apiCall(cfg, "POST", path, { body }); + return ok({ ...repoRef(r.data), clone_url: r.data.clone_url, ssh_url: r.data.ssh_url }); + }, + }, + { + name: "edit_repo", + description: "Edit repository settings (description, visibility, default branch, feature flags, archived state).", + inputSchema: repoParams({ + description: { type: "string" }, + private: { type: "boolean" }, + default_branch: { type: "string" }, + archived: { type: "boolean" }, + has_issues: { type: "boolean" }, + has_pull_requests: { type: "boolean" }, + has_wiki: { type: "boolean" }, + website: { type: "string" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const fields = ["description", "private", "default_branch", "archived", "has_issues", "has_pull_requests", "has_wiki", "website"]; + const body = pick(a, fields); + if (!Object.keys(body).length) throw new Error("Provide at least one field to change."); + const r = await apiCall(cfg, "PATCH", `/api/v1/repos/${owner}/${name}`, { body }); + // Echo the repo ref plus the post-edit value of every field that was changed. + return ok({ ...repoRef(r.data), ...pick(r.data, Object.keys(body)) }); + }, + }, + { + name: "delete_repo", + description: + "PERMANENTLY delete a repository including issues, PRs and releases. Destructive and unrecoverable: requires confirm=true and explicit user approval first.", + inputSchema: repoParams({ + confirm: { type: "boolean", description: "Must be true after explicit user confirmation" }, + }), + run: async (a, cfg) => { + if (a.confirm !== true) + throw new Error("Refusing to delete: set confirm=true only after the user explicitly approved deleting this repository."); + const { owner, name } = splitRepo(a.repo); + await apiCall(cfg, "DELETE", `/api/v1/repos/${owner}/${name}`); + return ok(`Deleted ${owner}/${name}.`); + }, + }, + { + name: "list_branches", + description: "List a repository's branches (name, head SHA, protected flag, last commit date and subject).", + inputSchema: repoParams(paged()), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/branches`, { query: q }); + return okList(r.data.map(branchRow), q, r); + }, + }, + { + name: "list_tags", + description: "List a repository's tags (name and commit SHA).", + inputSchema: repoParams(paged()), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/tags`, { query: q }); + return okList(r.data.map(tagRow), q, r); + }, + }, + + // ---- issues ---- + { + name: "list_issues", + description: + "List issues (optionally by state, labels, milestone). Pull requests are excluded. Rows carry number, title, state, author, labels, assignees, milestone, comment count and last-update date — no bodies; use get_issue for one issue's body and comments. For cross-repo search use search_issues.", + inputSchema: repoParams({ + state: { type: "string", enum: ["open", "closed", "all"], default: "open" }, + labels: { type: "string", description: "Comma-separated label names to filter by" }, + milestone: { type: "string", description: "Milestone title to filter by" }, + ...paged(), + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/issues`, { + query: { state: a.state || "open", type: "issues", labels: a.labels, milestones: a.milestone, ...q }, + }); + return okList(r.data.map((i) => issueRow(i)), q, r); + }, + }, + { + name: "search_issues", + description: + "Search issues and/or pull requests across every repository you can access, by keyword and filters. Rows include the repo name.", + inputSchema: { + type: "object", + properties: { + q: { type: "string", description: "Keyword(s) to match in title/body" }, + state: { type: "string", enum: ["open", "closed", "all"], default: "open" }, + type: { type: "string", enum: ["issues", "pulls"], description: "Omit for both" }, + labels: { type: "string", description: "Comma-separated label names" }, + owner: { type: "string", description: "Limit to repos of this user/org" }, + ...paged(), + }, + }, + run: async (a, cfg) => { + const q = pageArgs(a); + const r = await apiList(cfg, "/api/v1/repos/issues/search", { + query: { q: a.q, state: a.state || "open", type: a.type, labels: a.labels, owner: a.owner, ...q }, + }); + return okList(r.data.map((i) => issueRow(i, true)), q, r); + }, + }, + { + name: "get_issue", + description: + "Get one issue (or PR, same index space) with its most recent comments. Body is clipped at 6000 chars and each comment at 1500; set full=true to lift the clipping. Older comments are omitted beyond last_comments.", + inputSchema: repoParams({ + index: { type: "integer", description: "Issue number shown in the UI" }, + last_comments: { + type: "integer", + minimum: 0, + maximum: 100, + default: DEFAULT_COMMENTS, + description: "How many of the most recent comments to return (0 = none)", + }, + full: { type: "boolean", default: false, description: "Return body and comments unclipped" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const base = `/api/v1/repos/${owner}/${name}/issues/${a.index}`; + const issue = await apiCall(cfg, "GET", base); + const want = Math.max(0, Math.min(Number(a.last_comments ?? DEFAULT_COMMENTS), 100)); + const lines = [json(issueDetail(issue.data, a.full ? Infinity : BODY_MAX))]; + if (want > 0 && issue.data.comments > 0) { + // The comments endpoint is unpaginated and oldest-first: keep the tail. + const all = (await apiList(cfg, `${base}/comments`)).data; + const shown = all.slice(-want); + lines.push( + json({ + comments: all.length, + shown: shown.length, + omitted_older: nz(all.length - shown.length), + }), + ); + for (const c of shown) lines.push(json(commentRow(c, a.full ? Infinity : COMMENT_MAX))); + } + return textResult(lines.join("\n")); + }, + }, + { + name: "create_issue", + description: "Create an issue. Requires write:issue scope. Returns the new issue's number and URL.", + inputSchema: repoParams({ + title: { type: "string" }, + body: { type: "string", description: "Markdown body" }, + labels: { + type: "array", + items: { type: "integer" }, + description: "Label ids (from list_labels) to apply", + }, + assignees: { type: "array", items: { type: "string" } }, + milestone: { type: "integer", description: "Milestone id (from list_milestones)" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["title", "body", "labels", "assignees", "milestone"]); + const r = await apiCall(cfg, "POST", `/api/v1/repos/${owner}/${name}/issues`, { body }); + return ok(issueRef(r.data)); + }, + }, + { + name: "edit_issue", + description: + "Edit an issue's title/body/milestone, or change its state (state=open reopens, state=closed closes). Returns the updated number, state and URL.", + inputSchema: repoParams({ + index: { type: "integer" }, + title: { type: "string" }, + body: { type: "string" }, + state: { type: "string", enum: ["open", "closed"] }, + milestone: { type: "integer", description: "Milestone id (from list_milestones); 0 clears it" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["title", "body", "state", "milestone"]); + if (!Object.keys(body).length) throw new Error("Provide title, body, state, or milestone."); + const r = await apiCall(cfg, "PATCH", `/api/v1/repos/${owner}/${name}/issues/${a.index}`, { body }); + return ok(issueRef(r.data)); + }, + }, + { + name: "add_comment", + description: "Comment on an issue or pull request (both use the same index). Returns the comment id and URL.", + inputSchema: repoParams({ + index: { type: "integer", description: "Issue or PR number" }, + body: { type: "string", description: "Markdown comment" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const r = await apiCall(cfg, "POST", `/api/v1/repos/${owner}/${name}/issues/${a.index}/comments`, { + body: { body: a.body }, + }); + return ok({ id: r.data.id, url: r.data.html_url }); + }, + }, + + // ---- labels & milestones ---- + { + name: "list_labels", + description: "List a repository's labels (id, name, color, description).", + inputSchema: repoParams(paged()), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/labels`, { query: q }); + return okList(r.data.map(labelRow), q, r); + }, + }, + { + name: "create_label", + description: "Create a label. color is a hex value with or without '#'.", + inputSchema: repoParams({ + name: { type: "string" }, + color: { type: "string", description: "Hex color, e.g. d73a4a" }, + description: { type: "string" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["name", "color", "description"]); + const r = await apiCall(cfg, "POST", `/api/v1/repos/${owner}/${name}/labels`, { body }); + return ok(labelRow(r.data)); + }, + }, + { + name: "set_issue_labels", + description: + "REPLACE the complete label set of an issue or PR with the given label names (omit names to clear all labels). Returns the resulting label names.", + inputSchema: repoParams({ + index: { type: "integer" }, + labels: { type: "array", items: { type: "string" }, description: "Full desired label set (replaces existing)" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const r = await apiCall(cfg, "PUT", `/api/v1/repos/${owner}/${name}/issues/${a.index}/labels`, { + body: { labels: a.labels || [] }, + }); + return ok(JSON.stringify({ index: a.index, labels: names(r.data) })); + }, + }, + { + name: "list_milestones", + description: "List a repository's milestones (id, title, state, open/closed issue counts, due date).", + inputSchema: repoParams({ + state: { type: "string", enum: ["open", "closed", "all"], default: "open" }, + ...paged(), + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/milestones`, { + query: { state: a.state || "open", ...q }, + }); + return okList(r.data.map(milestoneRow), q, r); + }, + }, + { + name: "create_milestone", + description: "Create a milestone. due_on accepts YYYY-MM-DD or a full ISO timestamp.", + inputSchema: repoParams({ + title: { type: "string" }, + description: { type: "string" }, + due_on: { type: "string", description: "YYYY-MM-DD" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["title", "description"]); + if (a.due_on) body.due_on = isoDate(a.due_on); + const r = await apiCall(cfg, "POST", `/api/v1/repos/${owner}/${name}/milestones`, { body }); + return ok(milestoneRow(r.data)); + }, + }, + { + name: "edit_milestone", + description: "Edit a milestone (title, description, due date) or close/reopen it (state=closed/open).", + inputSchema: repoParams({ + number: { type: "integer", description: "Milestone id from list_milestones" }, + title: { type: "string" }, + description: { type: "string" }, + due_on: { type: "string", description: "YYYY-MM-DD" }, + state: { type: "string", enum: ["open", "closed"] }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["title", "description", "state"]); + if (a.due_on) body.due_on = isoDate(a.due_on); + const r = await apiCall(cfg, "PATCH", `/api/v1/repos/${owner}/${name}/milestones/${a.number}`, { body }); + return ok(milestoneRow(r.data)); + }, + }, + + // ---- pull requests ---- + { + name: "list_prs", + description: + "List pull requests, optionally by state. Rows carry number, title, state, author, head → base, labels, requested reviewers, comment count and last-update date — no bodies; use get_pr for details.", + inputSchema: repoParams({ + state: { type: "string", enum: ["open", "closed", "all"], default: "open" }, + ...paged(), + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/pulls`, { + query: { state: a.state || "open", ...q }, + }); + return okList(r.data.map(prRow), q, r); + }, + }, + { + name: "get_pr", + description: + "Get one pull request: state, mergeable, head/base, change stats, commit-status checks for the head commit, and the body (clipped at 6000 chars unless full=true). include_diff appends the raw diff, clipped at max_diff_chars. Read the comment thread with get_issue (same index).", + inputSchema: repoParams({ + index: { type: "integer" }, + include_diff: { type: "boolean", default: false }, + max_diff_chars: { + type: "integer", + minimum: 1000, + maximum: 35000, + default: DIFF_MAX, + description: "Clip the diff at this many characters", + }, + full: { type: "boolean", default: false, description: "Return the body unclipped" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const base = `/api/v1/repos/${owner}/${name}`; + const pr = (await apiCall(cfg, "GET", `${base}/pulls/${a.index}`)).data; + const out = prDetail(pr, a.full ? Infinity : BODY_MAX); + if (pr.head?.sha && pr.state === "open") { + try { + const st = (await apiCall(cfg, "GET", `${base}/commits/${pr.head.sha}/status`)).data; + const checks = (st?.statuses || []).map((s) => `${s.context}: ${s.status}`); + if (checks.length) out.checks = { state: st.state, items: checks.slice(0, 20) }; + } catch { + /* status endpoint unavailable or no statuses */ + } + } + // Keep the (potentially long) body last so the key fields lead. + const prBody = out.body; + delete out.body; + out.body = prBody; + let text = json(out); + if (a.include_diff) { + const max = Math.min(Number(a.max_diff_chars) || DIFF_MAX, 35000); + const diff = String((await apiCall(cfg, "GET", `${base}/pulls/${a.index}.diff`, { raw: true })).data || ""); + // Raw text, not JSON: escaping a diff inflates it by ~10–20%. + text += `\n--- diff (${diff.length} chars) ---\n`; + text += + diff.length > max + ? diff.slice(0, max) + `\n…[diff truncated, ${diff.length - max} more chars — ask about specific files instead of paging]` + : diff; + } + return textResult(text); + }, + }, + { + name: "create_pr", + description: + "Open a pull request. head is the source branch ('branch' within the same repo, or 'user:branch' from a fork); base is the target branch. Returns the new PR's number and URL.", + inputSchema: repoParams({ + title: { type: "string" }, + body: { type: "string" }, + base: { type: "string", description: "Target branch" }, + head: { type: "string", description: "Source branch, or 'user:branch' for forks" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["title", "body", "base", "head"]); + const r = await apiCall(cfg, "POST", `/api/v1/repos/${owner}/${name}/pulls`, { body }); + return ok(prRef(r.data)); + }, + }, + { + name: "edit_pr", + description: + "Edit a pull request's title/body or change its state (state=closed closes it). Returns the updated number, state and URL.", + inputSchema: repoParams({ + index: { type: "integer" }, + title: { type: "string" }, + body: { type: "string" }, + state: { type: "string", enum: ["open", "closed"] }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["title", "body", "state"]); + if (!Object.keys(body).length) throw new Error("Provide title, body, or state."); + const r = await apiCall(cfg, "PATCH", `/api/v1/repos/${owner}/${name}/pulls/${a.index}`, { body }); + return ok(prRef(r.data)); + }, + }, + { + name: "merge_pr", + description: + "Merge a pull request. style: merge (merge commit), rebase, rebase-merge, squash, or fast-forward-only. Check get_pr mergeable first. Optional merge_title and merge_message.", + inputSchema: repoParams({ + index: { type: "integer" }, + style: { + type: "string", + enum: ["merge", "rebase", "rebase-merge", "squash", "fast-forward-only"], + default: "merge", + }, + merge_title: { type: "string" }, + merge_message: { type: "string" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = { Do: a.style || "merge" }; + if (a.merge_title) body.MergeTitleField = a.merge_title; + if (a.merge_message) body.MergeMessageField = a.merge_message; + await apiCall(cfg, "POST", `/api/v1/repos/${owner}/${name}/pulls/${a.index}/merge`, { body }); + return ok(`Merged #${a.index} (${body.Do}).`); + }, + }, + + // ---- releases ---- + { + name: "list_releases", + description: + "List a repository's releases (tag, name, draft/prerelease, date, author, asset count, URL — no notes). Drafts and prereleases included where visible.", + inputSchema: repoParams(paged()), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/releases`, { query: q }); + return okList(r.data.map(releaseRow), q, r); + }, + }, + { + name: "create_release", + description: + "Create a release. tag_name creates the tag if absent (at target_commitish, defaulting to the default branch). Returns the release id, tag and URL.", + inputSchema: repoParams({ + tag_name: { type: "string" }, + name: { type: "string", description: "Release title (defaults to tag)" }, + body: { type: "string", description: "Markdown release notes" }, + draft: { type: "boolean", default: false }, + prerelease: { type: "boolean", default: false }, + target_commitish: { type: "string", description: "Branch or SHA the tag points at (when creating the tag)" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = pick(a, ["tag_name", "name", "body", "target_commitish"]); + body.draft = a.draft === true; + body.prerelease = a.prerelease === true; + const r = await apiCall(cfg, "POST", `/api/v1/repos/${owner}/${name}/releases`, { body }); + return ok(releaseRow(r.data)); + }, + }, + + // ---- organizations ---- + { + name: "list_orgs", + description: "List organizations you belong to.", + inputSchema: { type: "object", properties: paged() }, + run: async (a, cfg) => { + const q = pageArgs(a); + const r = await apiList(cfg, "/api/v1/user/orgs", { query: q }); + return okList(r.data.map(orgRow), q, r); + }, + }, + + // ---- Gitea Actions ---- + { + name: "list_action_runs", + description: + "List recent Gitea Actions task runs for a repository: workflow, run number, event, status, branch, commit, start time and duration (URL included for failures). Requires Gitea >= 1.25 and read:repository.", + inputSchema: repoParams(paged()), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const q = pageArgs(a); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/actions/tasks`, { query: q }); + return okList(r.data.map(taskRow), q, r); + }, + }, + { + name: "dispatch_workflow", + description: + "Trigger a manual (workflow_dispatch) run. workflow_id is the file name (e.g. release.yml); ref is the branch or tag to run on. The workflow must contain a workflow_dispatch trigger.", + inputSchema: repoParams({ + workflow_id: { type: "string", description: "Workflow file name, e.g. deploy.yml" }, + ref: { type: "string", description: "Branch or tag to dispatch on" }, + inputs: { type: "object", description: "Workflow inputs as key/value strings", additionalProperties: { type: "string" } }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const body = { ref: a.ref }; + if (a.inputs && Object.keys(a.inputs).length) body.inputs = a.inputs; + await apiCall( + cfg, + "POST", + `/api/v1/repos/${owner}/${name}/actions/workflows/${encodeURIComponent(a.workflow_id)}/dispatches`, + { body }, + ); + return ok(`Dispatched ${a.workflow_id} on ${a.ref}.`); + }, + }, + { + name: "list_secrets", + description: "List a repository's Gitea Actions secret NAMES (values are never returned).", + inputSchema: repoParams({}), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + const r = await apiList(cfg, `/api/v1/repos/${owner}/${name}/actions/secrets`); + return ok(JSON.stringify(r.data.map((s) => (s.created_at ? `${s.name} (${day(s.created_at)})` : s.name)))); + }, + }, + { + name: "set_secret", + description: + "Create or update one Gitea Actions secret. The value transits this conversation and tool logs — for high-value secrets prefer the Gitea UI.", + inputSchema: repoParams({ + name: { type: "string", description: "Secret name" }, + value: { type: "string", description: "Secret value" }, + }), + run: async (a, cfg) => { + const { owner, name } = splitRepo(a.repo); + await apiCall(cfg, "PUT", `/api/v1/repos/${owner}/${name}/actions/secrets/${encodeURIComponent(a.name)}`, { + body: { data: a.value }, + }); + return ok(`Secret ${a.name} set.`); + }, + }, +]; + +// --------------------------------------------------------- schema helpers --- + +function repoParams(extra) { + // "repo"-scoped property set; `required` is derived once from REQUIRED below. + return { + type: "object", + properties: { repo: { type: "string", description: 'Repository as "owner/name"' }, ...extra }, + }; +} + +// Required arguments per tool (every entry not listed defaults to ["repo"]). +const REQUIRED = { + whoami: [], + list_repos: [], + search_repos: ["q"], + search_issues: [], + create_repo: ["name"], + delete_repo: ["repo", "confirm"], + get_issue: ["repo", "index"], + create_issue: ["repo", "title"], + edit_issue: ["repo", "index"], + add_comment: ["repo", "index", "body"], + create_label: ["repo", "name", "color"], + set_issue_labels: ["repo", "index"], + create_milestone: ["repo", "title"], + edit_milestone: ["repo", "number"], + get_pr: ["repo", "index"], + create_pr: ["repo", "title", "base", "head"], + edit_pr: ["repo", "index"], + merge_pr: ["repo", "index"], + create_release: ["repo", "tag_name"], + list_orgs: [], + dispatch_workflow: ["repo", "workflow_id", "ref"], + set_secret: ["repo", "name", "value"], +}; +for (const t of TOOLS) { + t.inputSchema.required = [...(REQUIRED[t.name] ?? ["repo"])]; +} + +function paged() { + return { + limit: { type: "integer", minimum: 1, maximum: 50, default: DEFAULT_LIMIT }, + page: { type: "integer", minimum: 1, default: 1 }, + }; +} + +function pick(obj, keys) { + const out = {}; + for (const k of keys) if (obj[k] !== undefined && obj[k] !== null) out[k] = obj[k]; + return out; +} + +// ------------------------------------------------------------ jsonrpc core -- + +const PROTOCOL_VERSION = "2024-11-05"; + +function reply(id, result) { + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n"); +} + +function replyError(id, code, message) { + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } }) + "\n"); +} + +async function handle(method, params) { + switch (method) { + case "initialize": + return { + protocolVersion: params?.protocolVersion || PROTOCOL_VERSION, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: SERVER_NAME, version: SERVER_VERSION }, + }; + case "ping": + return {}; + case "tools/list": + return { + tools: TOOLS.map((t) => ({ + name: t.name, + description: t.description, + inputSchema: t.inputSchema, + })), + }; + case "tools/call": { + const name = params?.name; + const tool = TOOLS.find((t) => t.name === name); + if (!tool) throw { code: -32602, message: `Unknown tool "${name}"` }; + const cfg = await loadConfig(); + try { + return await tool.run(params.arguments || {}, cfg); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + return { + content: [{ type: "text", text: `Error: ${msg}` }], + isError: true, + }; + } + } + case "resources/list": + return { resources: [] }; + case "prompts/list": + return { prompts: [] }; + default: + throw { code: -32601, message: `Method not found: ${method}` }; + } +} + +let pending = 0; +let closing = false; + +const rl = createInterface({ input: process.stdin }); +rl.on("line", (line) => { + if (!line.trim()) return; + let msg; + try { + msg = JSON.parse(line); + } catch { + return; + } + if (msg === null || typeof msg !== "object" || msg.id === undefined || msg.id === null) return; // notification + pending++; + handle(msg.method, msg.params).then( + (result) => { + reply(msg.id, result); + done(); + }, + (e) => { + replyError(msg.id, e?.code ?? -32603, e?.message ?? String(e)); + done(); + }, + ); +}); +rl.on("close", () => { + closing = true; + if (pending === 0) process.exit(0); + // Safety valve: never hang on shutdown for a stuck request. + setTimeout(() => process.exit(0), 5000).unref(); +}); + +function done() { + pending--; + if (closing && pending === 0) process.exit(0); +} + +process.stderr.write(`[${SERVER_NAME}] mcp server ready (${TOOLS.length} tools)\n`); diff --git a/external_plugins/gitea/skills/actions/SKILL.md b/external_plugins/gitea/skills/actions/SKILL.md new file mode 100644 index 00000000..506c7c64 --- /dev/null +++ b/external_plugins/gitea/skills/actions/SKILL.md @@ -0,0 +1,62 @@ +--- +name: actions +description: Inspect Gitea Actions workflow runs, trigger workflow_dispatch pipelines, and manage repository Actions secrets. Use when the user wants CI/CD visibility or manual runs on a Gitea instance. +--- + +# Gitea Actions + +Work with Gitea Actions through the gitea MCP tools (`list_action_runs`, +`dispatch_workflow`, `list_secrets`, `set_secret`). Tool names may carry a +plugin prefix — match on the trailing name. + +## Arguments + +$ARGUMENTS + +**Format:** `[action] [args...]` + +- `runs` - List recent workflow runs (default action) +- `dispatch [ref]` - Trigger a manual run +- `secrets` - List secret names +- `set-secret ` - Create or update a secret + +## Resolving the repository + +Resolve `"owner/name"` from the explicit argument, else the `origin` remote +(`git remote get-url origin`), else ask. State it before any write. + +## Instructions + +### Runs + +`list_action_runs` — summarize each task's workflow name, run number, status +(success/failure/running), commit SHA, and duration. Surface failures with +their workflow + run number; logs themselves are in the web UI +(`/actions` on the repo), which the API tools here don't fetch. + +### Dispatch + +1. Confirm the workflow file (e.g. `deploy.yml` under + `.gitea/workflows/` or `.github/workflows/`) actually declares a + `workflow_dispatch:` trigger — check the file locally or via the web UI. +2. Confirm the `ref` (branch or tag, default the default branch) and any + `inputs` the workflow declares. +3. Show resolved repo, workflow, ref, and inputs; call `dispatch_workflow` + only after explicit confirmation. Success returns no run id — verify with + `list_action_runs` shortly after and report the new run. + +### Secrets + +- List names with `list_secrets` (values are never returned). +- `set_secret` creates or updates one secret. **The value passes through + this conversation and tool logs** — for high-value secrets, tell the user + to use the Gitea web UI (Settings → Actions → Secrets) instead, and only + proceed with their explicit go-ahead. + +## Error Handling + +- 404 on `list_action_runs` → the instance predates the tasks API + (needs Gitea ≥ 1.25) or Actions is disabled for the repo. +- 422 on dispatch → the workflow lacks a `workflow_dispatch` trigger, or an + input name is wrong. +- 403 → token lacks `write:repository`. diff --git a/external_plugins/gitea/skills/issue/SKILL.md b/external_plugins/gitea/skills/issue/SKILL.md new file mode 100644 index 00000000..eebfab75 --- /dev/null +++ b/external_plugins/gitea/skills/issue/SKILL.md @@ -0,0 +1,91 @@ +--- +name: issue +description: Create, view, list, close, reopen, and comment on Gitea issues, and manage the labels and milestones that organize them. Use when the user wants to track or organize repository work in Gitea, not when they are referring to a pull request itself. +--- + +# Gitea Issues, Labels, and Milestones + +Work with issues through the gitea MCP tools (`list_issues`, `get_issue`, +`create_issue`, `edit_issue`, `add_comment`, `list_labels`, `create_label`, +`set_issue_labels`, `list_milestones`, `create_milestone`, +`edit_milestone`). Tool names may carry a plugin prefix in the tool list — +match on the trailing name. + +## Arguments + +$ARGUMENTS + +**Format:** `[action] [args...]` + +- `create [title]` - Create an issue (default action) +- `view ` - View an issue with comments +- `list` - List open issues +- `close ` / `reopen ` - Change state +- `comment ` - Add a comment +- `label [args...]` - Manage labels +- `milestone [args...]` - Manage milestones + +## Resolving the repository + +Every tool takes `repo` as `"owner/name"`. Resolve it in this order: +explicit argument → the `origin` remote of the current directory +(`git remote get-url origin`, strip scheme/host and `.git`) → ask the user. +Always state the resolved `owner/name` before any write. + +## Instructions + +### Create Issue (default) + +1. If no title is given, ask or derive it from recent context. +2. Ask for the issue type (bug / feature / documentation / other) and draft a + Markdown body (Description, Steps to Reproduce / Use Case, Expected, + Actual, Environment for bugs). +3. Show the user the resolved repo, title, body, and any labels (`create_issue` + takes label **ids** from `list_labels`). Create with + `create_issue` **only after explicit confirmation**. +4. Report the resulting issue number and HTML URL. + +### View / List + +- `get_issue` returns the issue plus the 20 most recent comments + (`last_comments` to change; long bodies are clipped unless `full: true`) — + summarize state, labels, + milestone, assignees, and the recent comment thread. +- `list_issues` supports `state` (open/closed/all) and `labels` (comma + separated). Results are paginated (`page`, `limit` up to 50, `more` flags + another page). + +### Close / Reopen + +Fetch the issue first (`get_issue`), show title and state, get confirmation, +then `edit_issue` with `state: "closed"` (or `"open"` to reopen). + +### Comment + +Show the issue context, confirm the rendered text, then `add_comment`. The +same tool works on pull request numbers — issues and PRs share one index +space in Gitea. + +### Labels + +- List with `list_labels`. +- Create with `create_label` (`color` is hex, with or without `#`; + suggest `d73a4a` bug, `a2eeef` enhancement, `0075ca` documentation). +- `set_issue_labels` **replaces the complete label set** — read the current + labels with `get_issue` first, union/subtract as intended, and show the + final set to the user before calling. + +### Milestones + +- `list_milestones` shows progress counts; overdue is when `due_on` is past. +- Create with `create_milestone` (`due_on` accepts `YYYY-MM-DD`). +- Close/reopen with `edit_milestone` and `state`. +- To assign an issue to a milestone, use `create_issue`/`edit_issue` with the + milestone **id** from `list_milestones` (not the title). + +## Error Handling + +- 403 on issue endpoints usually means the token lacks `read:issue`/ + `write:issue` — suggest the gitea setup skill. +- 404 means the repo path is wrong or the token scope can't see it. +- If `whoami` has not run this session, run it before the first write. diff --git a/external_plugins/gitea/skills/pr/SKILL.md b/external_plugins/gitea/skills/pr/SKILL.md new file mode 100644 index 00000000..4aaa234e --- /dev/null +++ b/external_plugins/gitea/skills/pr/SKILL.md @@ -0,0 +1,76 @@ +--- +name: pr +description: Create, view, list, review, comment on, merge, and close Gitea pull requests. Use when the user wants to manage pull requests or review diffs in Gitea. +--- + +# Gitea Pull Requests + +Work with PRs through the gitea MCP tools (`list_prs`, `get_pr`, `create_pr`, +`edit_pr`, `merge_pr`, `add_comment`). Tool names may carry a plugin prefix — +match on the trailing name. + +## Arguments + +$ARGUMENTS + +**Format:** `[action] [args...]` + +- `list` - List open pull requests +- `view ` - View a PR (add `--diff` for the diff) +- `create ` - Open a pull request (default action) +- `merge <number>` - Merge a PR +- `close <number>` / `reopen <number>` - Change state +- `comment <number> <text>` - Comment on a PR + +## Resolving the repository + +Resolve `"owner/name"` from the explicit argument, else the `origin` remote +(`git remote get-url origin`), else ask. State it before any write. + +## Instructions + +### Create PR (default) + +1. Determine `head` (source branch containing the work) and `base` (target + branch). Verify `head` exists via `list_branches`; for same-repo branches + pass the bare name, for forks pass `"username:branch"`. +2. Draft title and body from the commits between base and head if the repo + is local (`git log --oneline base..head`). +3. Show resolved repo, head → base, title, and body. Create with `create_pr` + **only after explicit confirmation**. Report the PR number and URL. + +### View / List + +- `get_pr` returns the PR including `mergeable`, change stats and `checks` + (commit-status results for the head commit); the body is clipped at 6000 + chars unless `full: true`. `include_diff: true` appends the raw diff, + clipped at `max_diff_chars` (default 20000) — for large PRs ask about + specific files rather than paging the whole diff. +- Comments are not part of `get_pr`; use `add_comment` to reply and + `get_issue` (same index) to read the comment thread. + +### Merge + +1. `get_pr` first: confirm state is open, `mergeable` is true, and report + CI/status checks if present. +2. Confirm with the user: PR number/title, merge style + (`merge` commit / `rebase` / `rebase-merge` / `squash` / + `fast-forward-only` — default `merge`), and any custom merge title or + message. +3. Call `merge_pr`. If it fails with 405/conflict, re-fetch `merge_pr`-able + state and report the blocker (conflicts, changed base, checks) instead of + retrying blindly. + +### Close / Reopen / Comment + +Fetch first, show state and title, confirm, then `edit_pr` with +`state: "closed"` (or `"open"`). Comments via `add_comment` with the same +index as the PR. + +## Error Handling + +- 409/405 from `merge_pr` — read the message: usually conflicts or a + required-status failure. +- 403 usually means missing `write:repository` scope — suggest the gitea + setup skill. +- If `whoami` has not run this session, run it before the first write. diff --git a/external_plugins/gitea/skills/release/SKILL.md b/external_plugins/gitea/skills/release/SKILL.md new file mode 100644 index 00000000..db5c64a2 --- /dev/null +++ b/external_plugins/gitea/skills/release/SKILL.md @@ -0,0 +1,53 @@ +--- +name: release +description: List and create Gitea releases (tags, titles, and Markdown release notes). Use when the user wants to publish or review version releases on Gitea. +--- + +# Gitea Releases + +Work with releases through the gitea MCP tools (`list_releases`, +`create_release`, `list_tags`). Tool names may carry a plugin prefix — match +on the trailing name. + +## Arguments + +$ARGUMENTS + +**Format:** `[action] [args...]` + +- `list` - List releases (default action) +- `create <tag>` - Create a release + +## Resolving the repository + +Resolve `"owner/name"` from the explicit argument, else the `origin` remote +(`git remote get-url origin`), else ask. State it before any write. + +## Instructions + +### List + +`list_releases` — show tag, title, prerelease/draft flags, publish date, and +a one-line summary of the notes. Drafts are included when the token has +permission; label them clearly. + +### Create + +1. Gather: `tag_name` (required), title (defaults to the tag), release notes, + draft/prerelease flags, and — when the tag does not exist yet — + `target_commitish` (branch or SHA; defaults to the default branch). +2. Check `list_tags` / `list_releases` first: warn if the tag or an identical + release already exists. +3. Draft the release notes from commits since the previous release when the + repo is local (`git log --oneline <prev_tag>..`); show the user the full + draft — tag, target, title, notes, flags — and get explicit confirmation. +4. Call `create_release`; report the release URL. + +Release assets (attachments) are not covered by the API tools — point the +user to the web UI upload on the created release. + +## Error Handling + +- 409 → the tag or release already exists. +- 403 → token lacks `write:repository`. +- If `whoami` has not run this session, run it before creating. diff --git a/external_plugins/gitea/skills/repo/SKILL.md b/external_plugins/gitea/skills/repo/SKILL.md new file mode 100644 index 00000000..7fab7ed2 --- /dev/null +++ b/external_plugins/gitea/skills/repo/SKILL.md @@ -0,0 +1,70 @@ +--- +name: repo +description: Create, find, inspect, edit, and delete Gitea repositories, and list their branches and tags. Use when the user wants to manage repositories themselves rather than issues or PRs inside them. +--- + +# Gitea Repositories + +Work with repositories through the gitea MCP tools (`list_repos`, +`search_repos`, `get_repo`, `create_repo`, `edit_repo`, `delete_repo`, +`list_branches`, `list_tags`, `list_orgs`). Tool names may carry a plugin +prefix — match on the trailing name. + +## Arguments + +$ARGUMENTS + +**Format:** `[action] [args...]` + +- `list [org:<name>|user:<name>]` - List repositories (default: your own) +- `search <query>` - Search repositories by keyword +- `view <owner/name>` - Inspect one repository +- `create <name>` - Create a repository +- `edit <owner/name>` - Edit settings (description, visibility, …) +- `delete <owner/name>` - Delete a repository (destructive) +- `branches` / `tags` `<owner/name>` - List branches or tags + +## Instructions + +### List / Search + +- `list_repos` with `target: "mine"`, `target: "org"` (+ `org`), or + `target: "user"` (+ `username`). Paginated (`page`, `limit` ≤ 50). +- `search_repos` for keyword search instance-wide. +- Summarize as a compact table: full name, visibility, description, + updated_at, open issues. + +### View + +`get_repo` — report description, default branch, visibility, permissions, +size, and clone URLs. + +### Create + +Confirm with the user before calling `create_repo`: name, target (personal +account or an organization from `list_orgs`), description, visibility +(**defaults to private** — confirm before creating anything public), +default branch (`main`), and whether to auto-init with a README. Report the +clone URLs from the response. + +### Edit + +Show the current values from `get_repo` and the proposed changes; call +`edit_repo` only after confirmation. Editable: description, private, +default_branch, archived, has_issues, has_pull_requests, has_wiki, website. + +### Delete — destructive + +1. Require the user to state the full `owner/name` explicitly. +2. Show repository stats (from `get_repo`: size, open issues, stars) and + warn that issues, PRs, releases, and settings are deleted permanently + and the name becomes creatable by others. +3. Ask for a final explicit yes. Only then call `delete_repo` with + `confirm: true`. Never batch deletes. + +## Error Handling + +- 403 creating in an org → token lacks `write:organization`. +- 404 → check owner/name spelling, or the token can't see a private repo. +- Deleting a repo with a mirror or wiki still works; deleting the last copy + of anything unbacked-up is the user's call — surface the risk, don't block. diff --git a/external_plugins/gitea/skills/setup/SKILL.md b/external_plugins/gitea/skills/setup/SKILL.md new file mode 100644 index 00000000..db83e538 --- /dev/null +++ b/external_plugins/gitea/skills/setup/SKILL.md @@ -0,0 +1,75 @@ +--- +name: setup +description: Configure and verify Gitea authentication for the gitea plugin (instance URL plus scoped API token in ~/.config/gitea/mcp.json). Use when whoami fails, the token was rejected or lacks a scope, the user wants to switch instances, or before the first use of any other gitea skill. +--- + +# Set Up Gitea Access + +Guide the user through minting a scoped API token and configuring the gitea +MCP server, then verify with the `whoami` tool. The plugin is generic: any +Gitea instance works. + +## Arguments + +$ARGUMENTS + +**Format:** `[url]` — the Gitea base URL (e.g. `https://gitea.example.com`), +optional; default is the instance already configured. + +## Instructions + +1. Run the `whoami` tool. If it returns a user plus `token_scopes`, setup is + already working — report the user, URL, instance version, and scopes, then + stop. + +2. If whoami returns the not-configured error, agree on the instance URL with + the user, then have **the user** run these commands in their own terminal + (never ask them to paste a token into chat): + + ```bash + mkdir -p ~/.config/gitea + chmod 700 ~/.config/gitea + umask 177 + cat > ~/.config/gitea/mcp.json <<'EOF' + { + "url": "https://gitea.example.com", + "token": "PASTE_TOKEN_HERE" + } + EOF + ``` + + Then instruct them to mint the token first: in the Gitea web UI under + **Settings → Applications → Access Tokens → Generate New Token**, with the + token name of their choice and these scopes (Gitea 1.19+): + + - `read:user` (whoami) + - `read:repository` + `write:repository` (repos, branches, tags, reading + PRs/issues of private repos, releases) + - `read:issue` + `write:issue` (issues, labels, milestones, comments) + - `read:organization` (org listings and org repos; add + `write:organization` if they will create org repositories) + - `read:misc` (instance version — optional) + + Scope gotchas worth stating to the user: + + - A token with only `write:repository` (common for git push automation) + **cannot read issues** — 403s on issue endpoints are a scope problem, + not a permission problem. + - Scopes are per-token; generating a new token does not widen old ones. + + Environment-variable alternative (checked before the config file): + `GITEA_URL` and `GITEA_TOKEN` — useful for CI or ephemeral sessions. + +3. After the user confirms the file is written, run `whoami` again. Report: + the authenticated user, the URL, the instance version, and the exact + scopes the server reports. Cross-check the scopes against the list above + and flag any missing ones with the operations they would break. + +4. Do not create, modify, or delete any Gitea resource as part of setup. + +## Important + +- Never claim setup succeeded until `whoami` returns a user. +- Never ask the user to paste a token, password, or TOTP into chat; the token + goes from their browser into the config file, never through the agent. +- The config file must stay 0600 — the commands above enforce it via umask. diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..d77b8fc5 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,38 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "gitea", + "source": "./external_plugins/gitea", + "description": "Gitea integration with compact, context-friendly MCP output: token auth plus issues, pull requests, repositories, labels, milestones, releases, organizations and Gitea Actions through the Gitea REST API, including self-hosted instances.", + "description_i18n": { + "en": "Gitea integration with compact, context-friendly MCP output: token auth plus issues, pull requests, repositories, labels, milestones, releases, organizations and Gitea Actions through the Gitea REST API, including self-hosted instances.", + "zh-CN": "Gitea 集成,MCP 输出精简、节省上下文:基于令牌认证,通过 Gitea REST API 管理 Issue、Pull Request、仓库、标签、里程碑、Release、组织与 Gitea Actions,支持自托管实例。" + }, + "version": "0.2.0", + "author": { + "name": "Lloyd Culpepper", + "url": "https://github.com/OPVL" + }, + "category": "developer-tools", + "displayName": "Gitea", + "displayName_i18n": { + "en": "Gitea", + "zh-CN": "Gitea" + }, + "homepage": "https://github.com/OPVL/gitea-mcp", + "keywords": [ + "git", + "gitea", + "issues", + "pull-request", + "repository", + "releases", + "actions", + "self-hosted", + "mcp" + ] } ] } \ No newline at end of file