mirror of
https://gitea.com/gitea/gitea-mcp.git
synced 2026-08-03 23:59:23 +02:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 21aa4684d9 | |||
| c97c38996c | |||
| 18fcd663e0 | |||
| b1a6ed9f6b |
@@ -1,8 +1,12 @@
|
|||||||
- Use `make help` to find available development targets
|
- Use `make help` to find available development targets
|
||||||
- Run `make fmt` to format `.go` files, and run `make lint-go` to lint them
|
- Run `make fmt` to format `.go` files, and run `make lint-go` to lint them
|
||||||
- Run `make tidy` after any `go.mod` changes
|
- Run `make tidy` after any `go.mod` changes
|
||||||
|
- Run single go tests with `go test -run '^TestName$' ./modulepath/`
|
||||||
- Ensure no trailing whitespace in edited files
|
- Ensure no trailing whitespace in edited files
|
||||||
- Use Conventional Commits format for commit messages and PR titles (e.g. `type(scope): subject`)
|
- Use Conventional Commits for commit messages and PR titles, e.g. `type(scope): subject`; `!` before the colon if breaking. Use `test` type for test-only changes.
|
||||||
- Never force-push, amend, or squash unless asked. Use new commits and normal push for pull request updates
|
- Never force-push, amend, or squash unless asked. Use new commits and normal push for pull request updates
|
||||||
|
- Preserve existing code comments, do not remove or rewrite comments that are still relevant
|
||||||
|
- Keep comments short, prefer same-line, explain why, never narrate code
|
||||||
|
- Register new tools with `Tool.RegisterRead` or `Tool.RegisterWrite`, and add them to the tool tables in `README.md`, `README.zh-cn.md` and `README.zh-tw.md`
|
||||||
- Include authorship attribution in issue and pull request comments
|
- Include authorship attribution in issue and pull request comments
|
||||||
- Add `Co-Authored-By` lines to all commits, indicating name and model used
|
- Add `Co-Authored-By` lines to all commits, indicating name and model used
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ This project includes PowerShell and batch scripts to build the gitea-mcp applic
|
|||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
- Go 1.24 or later
|
- Go 1.26 or later
|
||||||
- Git (for version information)
|
- Git (for version information)
|
||||||
- PowerShell 5.1 or later (included with Windows 10/11)
|
- PowerShell 5.1 or later (included with Windows 10/11)
|
||||||
|
|
||||||
|
|||||||
@@ -1,78 +1 @@
|
|||||||
# CLAUDE.md
|
@AGENTS.md
|
||||||
|
|
||||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
||||||
|
|
||||||
## Development Commands
|
|
||||||
|
|
||||||
**Build**: `make build` - Build the gitea-mcp binary
|
|
||||||
**Install**: `make install` - Build and install to GOPATH/bin
|
|
||||||
**Clean**: `make clean` - Remove build artifacts
|
|
||||||
**Test**: `go test ./...` - Run all tests
|
|
||||||
**Hot reload**: `make dev` - Start development server with hot reload (requires air)
|
|
||||||
**Dependencies**: `make vendor` - Tidy and verify module dependencies
|
|
||||||
|
|
||||||
## Architecture Overview
|
|
||||||
|
|
||||||
This is a **Gitea MCP (Model Context Protocol) Server** written in Go that provides MCP tools for interacting with Gitea repositories, issues, pull requests, users, and more.
|
|
||||||
|
|
||||||
**Core Components**:
|
|
||||||
|
|
||||||
- `main.go` + `cmd/cmd.go`: CLI entry point and flag parsing
|
|
||||||
- `operation/operation.go`: Main server setup and tool registration
|
|
||||||
- `pkg/tool/tool.go`: Tool registry with read/write categorization
|
|
||||||
- `operation/*/`: Individual tool modules (user, repo, issue, pull, search, wiki, etc.)
|
|
||||||
|
|
||||||
**Transport Modes**:
|
|
||||||
|
|
||||||
- **stdio** (default): Standard input/output for MCP clients
|
|
||||||
- **http**: HTTP server mode on configurable port (default 8080)
|
|
||||||
|
|
||||||
**Authentication**:
|
|
||||||
|
|
||||||
- Global token via `--token` flag or `GITEA_ACCESS_TOKEN` env var
|
|
||||||
- HTTP mode supports per-request Bearer token override in Authorization header
|
|
||||||
- Token precedence: HTTP Authorization header > CLI flag > environment variable
|
|
||||||
|
|
||||||
**Tool Organization**:
|
|
||||||
|
|
||||||
- Tools are categorized as read-only or write operations
|
|
||||||
- `--read-only` flag exposes only read tools
|
|
||||||
- Tool modules register via `Tool.RegisterRead()` and `Tool.RegisterWrite()`
|
|
||||||
|
|
||||||
**Key Configuration**:
|
|
||||||
|
|
||||||
- Default Gitea host: `https://gitea.com` (override with `--host` or `GITEA_HOST`)
|
|
||||||
- Environment variables can override CLI flags: `MCP_MODE`, `GITEA_READONLY`, `GITEA_DEBUG`, `GITEA_INSECURE`
|
|
||||||
- Logs are written to `~/.gitea-mcp/gitea-mcp.log` with rotation
|
|
||||||
|
|
||||||
## Available Tools
|
|
||||||
|
|
||||||
The server provides 45 MCP tools covering:
|
|
||||||
|
|
||||||
- **User**: get_me, get_user_orgs
|
|
||||||
- **Search**: search_users, search_repos, search_org_teams
|
|
||||||
- **Repository**: create_repo, fork_repo, list_my_repos
|
|
||||||
- **Branches**: list_branches, create_branch, delete_branch
|
|
||||||
- **Tags**: list_tags, get_tag, create_tag, delete_tag
|
|
||||||
- **Files**: get_file_contents, get_dir_contents, create_or_update_file, delete_file
|
|
||||||
- **Commits**: list_commits
|
|
||||||
- **Issues**: list_issues, issue_read, issue_write
|
|
||||||
- **Pull Requests**: list_pull_requests, pull_request_read, pull_request_write, pull_request_review_write
|
|
||||||
- **Labels**: label_read, label_write
|
|
||||||
- **Milestones**: milestone_read, milestone_write
|
|
||||||
- **Releases**: list_releases, get_release, get_latest_release, create_release, delete_release
|
|
||||||
- **Wiki**: wiki_read, wiki_write
|
|
||||||
- **Time Tracking**: timetracking_read, timetracking_write
|
|
||||||
- **Actions Runs**: actions_run_read, actions_run_write
|
|
||||||
- **Actions Config**: actions_config_read, actions_config_write
|
|
||||||
- **Version**: get_gitea_mcp_server_version
|
|
||||||
|
|
||||||
## Common Development Patterns
|
|
||||||
|
|
||||||
**Testing**: Use `go test ./operation -run TestFunctionName` for specific tests
|
|
||||||
|
|
||||||
**Token Context**: HTTP requests use `pkg/context.TokenContextKey` for request-scoped token access
|
|
||||||
|
|
||||||
**Flag Access**: All packages access configuration via global variables in `pkg/flag/flag.go`
|
|
||||||
|
|
||||||
**Graceful Shutdown**: HTTP mode implements graceful shutdown with 10-second timeout on SIGTERM/SIGINT
|
|
||||||
|
|||||||
@@ -2,58 +2,27 @@
|
|||||||
|
|
||||||
[繁體中文](README.zh-tw.md) | [简体中文](README.zh-cn.md)
|
[繁體中文](README.zh-tw.md) | [简体中文](README.zh-cn.md)
|
||||||
|
|
||||||
**Gitea MCP Server** is an integration plugin designed to connect Gitea with Model Context Protocol (MCP) systems. This allows for seamless command execution and repository management through an MCP-compatible chat interface.
|
**Gitea MCP Server** connects a [Gitea](https://about.gitea.com) instance to [Model Context Protocol](https://modelcontextprotocol.io) clients, so repositories, issues, pull requests and more can be browsed and managed from an MCP-compatible chat interface.
|
||||||
|
|
||||||
[](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
|
[](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
|
||||||
|
|
||||||
## Table of Contents
|
## Installation
|
||||||
|
|
||||||
- [Gitea MCP Server](#gitea-mcp-server)
|
Download a binary from the [releases page](https://gitea.com/gitea/gitea-mcp/releases) and put it in your `PATH`, use the `docker.gitea.com/gitea-mcp-server` image, or build from source into `$GOPATH/bin` with `make` and Go 1.26 or later:
|
||||||
- [Table of Contents](#table-of-contents)
|
|
||||||
- [What is Gitea?](#what-is-gitea)
|
|
||||||
- [What is MCP?](#what-is-mcp)
|
|
||||||
- [🚧 Installation](#-installation)
|
|
||||||
- [Usage with Claude Code](#usage-with-claude-code)
|
|
||||||
- [Usage with VS Code](#usage-with-vs-code)
|
|
||||||
- [Usage with Mistral Vibe](#usage-with-mistral-vibe)
|
|
||||||
- [📥 Download the official binary release](#-download-the-official-binary-release)
|
|
||||||
- [🔧 Build from Source](#-build-from-source)
|
|
||||||
- [📁 Add to PATH](#-add-to-path)
|
|
||||||
- [🚀 Usage](#-usage)
|
|
||||||
- [✅ Available Tools](#-available-tools)
|
|
||||||
- [🐛 Debugging](#-debugging)
|
|
||||||
- [🛠 Troubleshooting](#-troubleshooting)
|
|
||||||
|
|
||||||
## What is Gitea?
|
```bash
|
||||||
|
git clone https://gitea.com/gitea/gitea-mcp.git
|
||||||
Gitea is a community-managed lightweight code hosting solution written in Go. It is published under the MIT license. Gitea provides Git hosting including a repository viewer, issue tracking, pull requests, and more.
|
cd gitea-mcp
|
||||||
|
make install
|
||||||
## What is MCP?
|
|
||||||
|
|
||||||
Model Context Protocol (MCP) is a protocol that allows for the integration of various tools and systems through a chat interface. It enables seamless command execution and management of repositories, users, and other resources.
|
|
||||||
|
|
||||||
## 🚧 Installation
|
|
||||||
|
|
||||||
### Usage with OpenCode (opencode.ai)
|
|
||||||
|
|
||||||
Add a snippet like the following in the "mcp" top-level object (add one if you don't have any):
|
|
||||||
|
|
||||||
```json
|
|
||||||
"gitea-mcp": {
|
|
||||||
"enabled": true,
|
|
||||||
"type": "local",
|
|
||||||
"command": [
|
|
||||||
"gitea-mcp",
|
|
||||||
"-t", "stdio",
|
|
||||||
"-H", "https://git.your-domain.org",
|
|
||||||
"-T", "<your personal access token>"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Usage with Claude Code
|
## Configuration
|
||||||
|
|
||||||
This method uses `go run` and requires [Go](https://go.dev) to be installed.
|
Pass the Gitea host and access token as command-line flags or environment variables, flags take precedence. Run `gitea-mcp --help` for the full list of flags and environment variables. Logs are written to `$HOME/.gitea-mcp/gitea-mcp.log`, add `-d` for debug logging.
|
||||||
|
|
||||||
|
### Claude Code
|
||||||
|
|
||||||
|
Runs the server through `go run` and requires [Go](https://go.dev):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
claude mcp add --transport stdio --scope user gitea \
|
claude mcp add --transport stdio --scope user gitea \
|
||||||
@@ -62,15 +31,9 @@ claude mcp add --transport stdio --scope user gitea \
|
|||||||
-- go run gitea.com/gitea/gitea-mcp@latest -t stdio
|
-- go run gitea.com/gitea/gitea-mcp@latest -t stdio
|
||||||
```
|
```
|
||||||
|
|
||||||
### Usage with VS Code
|
### VS Code
|
||||||
|
|
||||||
For quick installation, use one of the one-click install buttons at the top of this README.
|
Use the install buttons at the top of this README, or add the block below to your User Settings (JSON), reachable via `Ctrl + Shift + P` and `Preferences: Open User Settings (JSON)`. It also works in a workspace `.vscode/mcp.json`, where the `mcp` key is omitted.
|
||||||
|
|
||||||
For manual installation, add the following JSON block to your User Settings (JSON) file in VS Code. You can do this by pressing `Ctrl + Shift + P` and typing `Preferences: Open User Settings (JSON)`.
|
|
||||||
|
|
||||||
Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others.
|
|
||||||
|
|
||||||
> Note that the `mcp` key is not needed in the `.vscode/mcp.json` file.
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -86,14 +49,7 @@ Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace
|
|||||||
"servers": {
|
"servers": {
|
||||||
"gitea-mcp": {
|
"gitea-mcp": {
|
||||||
"command": "docker",
|
"command": "docker",
|
||||||
"args": [
|
"args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "docker.gitea.com/gitea-mcp-server"],
|
||||||
"run",
|
|
||||||
"-i",
|
|
||||||
"--rm",
|
|
||||||
"-e",
|
|
||||||
"GITEA_ACCESS_TOKEN",
|
|
||||||
"docker.gitea.com/gitea-mcp-server"
|
|
||||||
],
|
|
||||||
"env": {
|
"env": {
|
||||||
"GITEA_ACCESS_TOKEN": "${input:gitea_token}"
|
"GITEA_ACCESS_TOKEN": "${input:gitea_token}"
|
||||||
}
|
}
|
||||||
@@ -103,84 +59,50 @@ Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Usage with Mistral Vibe
|
### OpenCode
|
||||||
|
|
||||||
Add the following configuration to your Mistral Vibe MCP configuration file (`~/.vibe/config.toml`):
|
Add the following to the top-level `mcp` object of your [OpenCode](https://opencode.ai) config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"gitea-mcp": {
|
||||||
|
"enabled": true,
|
||||||
|
"type": "local",
|
||||||
|
"command": [
|
||||||
|
"gitea-mcp",
|
||||||
|
"-t", "stdio",
|
||||||
|
"-H", "https://gitea.com",
|
||||||
|
"-T", "<your personal access token>"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mistral Vibe
|
||||||
|
|
||||||
|
Add the following to `~/.vibe/config.toml`:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[[mcp_servers]]
|
[[mcp_servers]]
|
||||||
name = "gitea"
|
name = "gitea"
|
||||||
transport = "stdio"
|
transport = "stdio"
|
||||||
command = "docker"
|
command = "docker"
|
||||||
args = [
|
args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "docker.gitea.com/gitea-mcp-server"]
|
||||||
"run",
|
|
||||||
"--rm",
|
|
||||||
"-i",
|
|
||||||
"-e",
|
|
||||||
"GITEA_ACCESS_TOKEN",
|
|
||||||
"-e",
|
|
||||||
"GITEA_HOST",
|
|
||||||
"docker.gitea.com/gitea-mcp-server",
|
|
||||||
]
|
|
||||||
|
|
||||||
[mcp_servers.env]
|
[mcp_servers.env]
|
||||||
GITEA_ACCESS_TOKEN = "TOKEN"
|
GITEA_ACCESS_TOKEN = "TOKEN"
|
||||||
GITEA_HOST = "https://gitea.com"
|
GITEA_HOST = "https://gitea.com"
|
||||||
```
|
```
|
||||||
|
|
||||||
### 📥 Download the official binary release
|
### Other clients
|
||||||
|
|
||||||
You can download the official release from [official Gitea MCP binary releases](https://gitea.com/gitea/gitea-mcp/releases).
|
Clients such as Cursor take either a stdio command:
|
||||||
|
|
||||||
### 🔧 Build from Source
|
|
||||||
|
|
||||||
You can download the source code by cloning the repository using Git:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone https://gitea.com/gitea/gitea-mcp.git
|
|
||||||
```
|
|
||||||
|
|
||||||
Before building, make sure you have the following installed:
|
|
||||||
|
|
||||||
- make
|
|
||||||
- Golang (Go 1.24 or later recommended)
|
|
||||||
|
|
||||||
Then run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
make install
|
|
||||||
```
|
|
||||||
|
|
||||||
### 📁 Add to PATH
|
|
||||||
|
|
||||||
After installing, copy the binary gitea-mcp to a directory included in your system's PATH. For example:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp gitea-mcp /usr/local/bin/
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🚀 Usage
|
|
||||||
|
|
||||||
This example is for Cursor, you can also use plugins in VSCode.
|
|
||||||
To configure the MCP server for Gitea, add the following to your MCP configuration file:
|
|
||||||
|
|
||||||
- **stdio mode**
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"gitea": {
|
"gitea": {
|
||||||
"command": "gitea-mcp",
|
"command": "gitea-mcp",
|
||||||
"args": [
|
"args": ["-t", "stdio", "--host", "https://gitea.com"],
|
||||||
"-t",
|
|
||||||
"stdio",
|
|
||||||
"--host",
|
|
||||||
"https://gitea.com"
|
|
||||||
// "--token", "<your personal access token>"
|
|
||||||
],
|
|
||||||
"env": {
|
"env": {
|
||||||
// "GITEA_HOST": "https://gitea.com",
|
|
||||||
// "GITEA_INSECURE": "true",
|
|
||||||
"GITEA_ACCESS_TOKEN": "<your personal access token>"
|
"GITEA_ACCESS_TOKEN": "<your personal access token>"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,7 +110,7 @@ To configure the MCP server for Gitea, add the following to your MCP configurati
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- **http mode**
|
or an http endpoint, for a server started with `gitea-mcp -t http --port 8080`:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -203,132 +125,74 @@ To configure the MCP server for Gitea, add the following to your MCP configurati
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Default log path**: `$HOME/.gitea-mcp/gitea-mcp.log`
|
Once configured, try `list all my repositories` in the chat box.
|
||||||
|
|
||||||
> [!NOTE]
|
## Available Tools
|
||||||
> You can provide your Gitea host and access token either as command-line arguments or environment variables.
|
|
||||||
> Command-line arguments have the highest priority
|
|
||||||
|
|
||||||
> [!NOTE]
|
| Tool | Scope | Access | Description |
|
||||||
> Many tools support `page` and `perPage` parameters for pagination. The maximum effective page size is determined by the Gitea server's `[api].MAX_RESPONSE_ITEMS` setting (default: **50**). Requesting a `perPage` value higher than this limit will be silently capped by the server.
|
| :--------------------------- | :----------- | :----- | :----------------------------------------------------------------------------------------- |
|
||||||
|
| get_gitea_mcp_server_version | version | Read | Get the Gitea MCP server version |
|
||||||
|
| get_me | user | Read | Get the current authenticated user |
|
||||||
|
| get_user_orgs | user | Read | List the current user's organizations |
|
||||||
|
| search_users | search | Read | Search for users |
|
||||||
|
| search_org_teams | search | Read | Search teams within an organization |
|
||||||
|
| search_repos | search | Read | Search for repositories |
|
||||||
|
| search_issues | search | Read | Search issues and pull requests across repositories |
|
||||||
|
| notification_read | notification | Read | Read notifications: list (optionally scoped to a repo) or get a thread by ID |
|
||||||
|
| notification_write | notification | Write | Mark a notification or all notifications as read |
|
||||||
|
| label_read | label | Read | Read repository or organization labels |
|
||||||
|
| label_write | label | Write | Write labels (repo or org): create, edit, delete |
|
||||||
|
| milestone_read | milestone | Read | Read milestones: get one or list |
|
||||||
|
| milestone_write | milestone | Write | Write milestones: create, update, delete |
|
||||||
|
| wiki_read | wiki | Read | Read wiki: list pages, get content, revision history |
|
||||||
|
| wiki_write | wiki | Write | Write wiki pages: create, update, delete |
|
||||||
|
| timetracking_read | timetracking | Read | Read time tracking: issue/repo times, active stopwatches, your tracked times |
|
||||||
|
| timetracking_write | timetracking | Write | Write time tracking: stopwatches and entries |
|
||||||
|
| package_read | packages | Read | Read package registry: list packages, list versions, or get a version |
|
||||||
|
| package_write | packages | Write | Delete a package version (irreversible) |
|
||||||
|
| list_issues | issue | Read | List repository issues |
|
||||||
|
| attachment_read | issue | Read | Read issue/comment attachments: list metadata, get metadata, or download content |
|
||||||
|
| issue_read | issue | Read | Read issue: details, comments, or labels |
|
||||||
|
| issue_write | issue | Write | Write issues: create, update, manage comments and labels |
|
||||||
|
| list_pull_requests | pull_request | Read | List repository pull requests |
|
||||||
|
| pull_request_read | pull_request | Read | Read pull request: details, diff, changed files, head commit status, reviews |
|
||||||
|
| pull_request_write | pull_request | Write | Write pull requests: create, update, close, reopen, merge, update branch, manage reviewers |
|
||||||
|
| pull_request_review_write | pull_request | Write | Write PR reviews: create, submit, delete, dismiss |
|
||||||
|
| actions_config_read | actions | Read | Read Actions secrets and variables |
|
||||||
|
| actions_config_write | actions | Write | Write Actions secrets and variables: upsert, create, update, delete |
|
||||||
|
| actions_run_read | actions | Read | Read Actions workflows, runs, jobs, logs, and artifacts |
|
||||||
|
| actions_run_write | actions | Write | Write Actions runs: dispatch, cancel, rerun |
|
||||||
|
| create_repo | repository | Write | Create a new repository |
|
||||||
|
| fork_repo | repository | Write | Fork a repository |
|
||||||
|
| list_my_repos | repository | Read | List repositories owned by the current user |
|
||||||
|
| list_org_repos | repository | Read | List repositories in an organization |
|
||||||
|
| get_repository_tree | repository | Read | Get the repository file tree |
|
||||||
|
| get_file_contents | file | Read | Get file content and metadata |
|
||||||
|
| get_dir_contents | file | Read | Get the entries in a directory |
|
||||||
|
| create_or_update_file | file | Write | Create or update a file (provide sha to update an existing file) |
|
||||||
|
| delete_file | file | Write | Delete a file |
|
||||||
|
| create_branch | branch | Write | Create a new branch |
|
||||||
|
| delete_branch | branch | Write | Delete a branch |
|
||||||
|
| list_branches | branch | Read | List repository branches |
|
||||||
|
| create_tag | tag | Write | Create a tag |
|
||||||
|
| delete_tag | tag | Write | Delete a tag |
|
||||||
|
| get_tag | tag | Read | Get tag details |
|
||||||
|
| list_tags | tag | Read | List repository tags |
|
||||||
|
| list_commits | commit | Read | List repository commits |
|
||||||
|
| get_commit | commit | Read | Get commit details |
|
||||||
|
| create_release | release | Write | Create a release |
|
||||||
|
| delete_release | release | Write | Delete a release |
|
||||||
|
| get_release | release | Read | Get a release by ID |
|
||||||
|
| get_latest_release | release | Read | Get the latest release |
|
||||||
|
| list_releases | release | Read | List repository releases |
|
||||||
|
|
||||||
Once everything is set up, try typing the following in your MCP-compatible chatbox:
|
> **Note:** Several tools are consolidated, action-based tools, a single tool exposes multiple operations through a `method` parameter. Tools with `Write` access are hidden when the server runs in read-only mode (`-r` / `GITEA_READONLY`), and the exposed tool set can be filtered by scope with `-S` / `--scope` (`GITEA_SCOPES`) and/or by individual tool name with `-O` / `--tools` (`GITEA_TOOLS`).
|
||||||
|
|
||||||
```text
|
With neither flag set, every tool loads. `--scope` limits loading to tools whose Scope column value is in the given list; `--tools` limits loading to the named tools; setting both loads the union of the selected scopes and the individually named tools. Unknown scope names are ignored with a startup warning.
|
||||||
list all my repositories
|
|
||||||
|
```bash
|
||||||
|
gitea-mcp -S issue,pull_request
|
||||||
|
gitea-mcp --scope repository,branch --tools get_me
|
||||||
```
|
```
|
||||||
|
|
||||||
## ✅ Available Tools
|
Many tools accept `page` and `per_page` for pagination. The maximum effective page size is the Gitea server's `[api].MAX_RESPONSE_ITEMS` setting (default **50**), larger values are silently capped.
|
||||||
|
|
||||||
The Gitea MCP Server supports the following tools:
|
|
||||||
|
|
||||||
| Tool | Scope | Description |
|
|
||||||
| :-------------------------------: | :----------: | :------------------------------------------------------: |
|
|
||||||
| get_my_user_info | User | Get the information of the authenticated user |
|
|
||||||
| get_user_orgs | User | Get organizations associated with the authenticated user |
|
|
||||||
| create_repo | Repository | Create a new repository |
|
|
||||||
| fork_repo | Repository | Fork a repository |
|
|
||||||
| list_my_repos | Repository | List all repositories owned by the authenticated user |
|
|
||||||
| create_branch | Branch | Create a new branch |
|
|
||||||
| delete_branch | Branch | Delete a branch |
|
|
||||||
| list_branches | Branch | List all branches in a repository |
|
|
||||||
| create_release | Release | Create a new release in a repository |
|
|
||||||
| delete_release | Release | Delete a release from a repository |
|
|
||||||
| get_release | Release | Get a release |
|
|
||||||
| get_latest_release | Release | Get the latest release in a repository |
|
|
||||||
| list_releases | Release | List all releases in a repository |
|
|
||||||
| create_tag | Tag | Create a new tag |
|
|
||||||
| delete_tag | Tag | Delete a tag |
|
|
||||||
| get_tag | Tag | Get a tag |
|
|
||||||
| list_tags | Tag | List all tags in a repository |
|
|
||||||
| list_repo_commits | Commit | List all commits in a repository |
|
|
||||||
| get_file_content | File | Get the content and metadata of a file |
|
|
||||||
| get_dir_content | File | Get a list of entries in a directory |
|
|
||||||
| create_file | File | Create a new file |
|
|
||||||
| update_file | File | Update an existing file |
|
|
||||||
| delete_file | File | Delete a file |
|
|
||||||
| get_issue_by_index | Issue | Get an issue by its index |
|
|
||||||
| list_repo_issues | Issue | List all issues in a repository |
|
|
||||||
| create_issue | Issue | Create a new issue |
|
|
||||||
| create_issue_comment | Issue | Create a comment on an issue |
|
|
||||||
| edit_issue | Issue | Edit a issue |
|
|
||||||
| edit_issue_comment | Issue | Edit a comment on an issue |
|
|
||||||
| get_issue_comments_by_index | Issue | Get comments of an issue by its index |
|
|
||||||
| get_pull_request_by_index | Pull Request | Get a pull request by its index |
|
|
||||||
| get_pull_request_diff | Pull Request | Get a pull request diff |
|
|
||||||
| list_repo_pull_requests | Pull Request | List all pull requests in a repository |
|
|
||||||
| create_pull_request | Pull Request | Create a new pull request |
|
|
||||||
| create_pull_request_reviewer | Pull Request | Add reviewers to a pull request |
|
|
||||||
| delete_pull_request_reviewer | Pull Request | Remove reviewers from a pull request |
|
|
||||||
| list_pull_request_reviews | Pull Request | List all reviews for a pull request |
|
|
||||||
| get_pull_request_review | Pull Request | Get a specific review by ID |
|
|
||||||
| list_pull_request_review_comments | Pull Request | List inline comments for a review |
|
|
||||||
| create_pull_request_review | Pull Request | Create a review with optional inline comments |
|
|
||||||
| submit_pull_request_review | Pull Request | Submit a pending review |
|
|
||||||
| delete_pull_request_review | Pull Request | Delete a review |
|
|
||||||
| dismiss_pull_request_review | Pull Request | Dismiss a review with optional message |
|
|
||||||
| merge_pull_request | Pull Request | Merge a pull request |
|
|
||||||
| search_users | User | Search for users |
|
|
||||||
| search_org_teams | Organization | Search for teams in an organization |
|
|
||||||
| list_org_labels | Organization | List labels defined at organization level |
|
|
||||||
| create_org_label | Organization | Create a label in an organization |
|
|
||||||
| edit_org_label | Organization | Edit a label in an organization |
|
|
||||||
| delete_org_label | Organization | Delete a label in an organization |
|
|
||||||
| search_repos | Repository | Search for repositories |
|
|
||||||
| list_repo_action_secrets | Actions | List repository Actions secrets (metadata only) |
|
|
||||||
| upsert_repo_action_secret | Actions | Create/update (upsert) a repository Actions secret |
|
|
||||||
| delete_repo_action_secret | Actions | Delete a repository Actions secret |
|
|
||||||
| list_org_action_secrets | Actions | List organization Actions secrets (metadata only) |
|
|
||||||
| upsert_org_action_secret | Actions | Create/update (upsert) an organization Actions secret |
|
|
||||||
| delete_org_action_secret | Actions | Delete an organization Actions secret |
|
|
||||||
| list_repo_action_variables | Actions | List repository Actions variables |
|
|
||||||
| get_repo_action_variable | Actions | Get a repository Actions variable |
|
|
||||||
| create_repo_action_variable | Actions | Create a repository Actions variable |
|
|
||||||
| update_repo_action_variable | Actions | Update a repository Actions variable |
|
|
||||||
| delete_repo_action_variable | Actions | Delete a repository Actions variable |
|
|
||||||
| list_org_action_variables | Actions | List organization Actions variables |
|
|
||||||
| get_org_action_variable | Actions | Get an organization Actions variable |
|
|
||||||
| create_org_action_variable | Actions | Create an organization Actions variable |
|
|
||||||
| update_org_action_variable | Actions | Update an organization Actions variable |
|
|
||||||
| delete_org_action_variable | Actions | Delete an organization Actions variable |
|
|
||||||
| list_repo_action_workflows | Actions | List repository Actions workflows |
|
|
||||||
| get_repo_action_workflow | Actions | Get a repository Actions workflow |
|
|
||||||
| dispatch_repo_action_workflow | Actions | Trigger (dispatch) a repository Actions workflow |
|
|
||||||
| list_repo_action_runs | Actions | List repository Actions runs |
|
|
||||||
| get_repo_action_run | Actions | Get a repository Actions run |
|
|
||||||
| cancel_repo_action_run | Actions | Cancel a repository Actions run |
|
|
||||||
| rerun_repo_action_run | Actions | Rerun a repository Actions run |
|
|
||||||
| list_repo_action_jobs | Actions | List repository Actions jobs |
|
|
||||||
| list_repo_action_run_jobs | Actions | List Actions jobs for a run |
|
|
||||||
| get_repo_action_job_log_preview | Actions | Get a job log preview (tail/limited) |
|
|
||||||
| download_repo_action_job_log | Actions | Download a job log to a file |
|
|
||||||
| list_repo_action_artifacts | Actions | List repository Actions artifacts |
|
|
||||||
| list_repo_action_run_artifacts | Actions | List Actions artifacts for a run |
|
|
||||||
| get_repo_action_artifact | Actions | Get a repository Actions artifact |
|
|
||||||
| download_repo_action_artifact | Actions | Download an Actions artifact zip to a file |
|
|
||||||
| get_gitea_mcp_server_version | Server | Get the version of the Gitea MCP Server |
|
|
||||||
| list_wiki_pages | Wiki | List all wiki pages in a repository |
|
|
||||||
| get_wiki_page | Wiki | Get a wiki page content and metadata |
|
|
||||||
| get_wiki_revisions | Wiki | Get revisions history of a wiki page |
|
|
||||||
| create_wiki_page | Wiki | Create a new wiki page |
|
|
||||||
| update_wiki_page | Wiki | Update an existing wiki page |
|
|
||||||
| delete_wiki_page | Wiki | Delete a wiki page |
|
|
||||||
|
|
||||||
## 🐛 Debugging
|
|
||||||
|
|
||||||
To enable debug mode, add the `-d` flag when running the Gitea MCP Server with http mode:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
./gitea-mcp -t http [--port 8080] --token <your personal access token> -d
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🛠 Troubleshooting
|
|
||||||
|
|
||||||
If you encounter any issues, here are some common troubleshooting steps:
|
|
||||||
|
|
||||||
1. **Check your PATH**: Ensure that the `gitea-mcp` binary is in a directory included in your system's PATH.
|
|
||||||
2. **Verify dependencies**: Make sure you have all the required dependencies installed, such as `make` and `Golang`.
|
|
||||||
3. **Review configuration**: Double-check your MCP configuration file for any errors or missing information.
|
|
||||||
4. **Consult logs**: Check the logs for any error messages or warnings that can provide more information about the issue.
|
|
||||||
|
|
||||||
Enjoy exploring and managing your Gitea repositories via chat!
|
|
||||||
|
|||||||
+108
-169
@@ -2,40 +2,27 @@
|
|||||||
|
|
||||||
[English](README.md) | [繁體中文](README.zh-tw.md)
|
[English](README.md) | [繁體中文](README.zh-tw.md)
|
||||||
|
|
||||||
**Gitea MCP 服务器** 是一个集成插件,旨在将 Gitea 与 Model Context Protocol (MCP) 系统连接起来。这允许通过 MCP 兼容的聊天界面无缝执行命令和管理仓库。
|
**Gitea MCP 服务器** 将 [Gitea](https://about.gitea.com) 实例接入 [Model Context Protocol](https://modelcontextprotocol.io) 客户端,让仓库、问题、拉取请求等都能在兼容 MCP 的聊天界面中浏览和管理。
|
||||||
|
|
||||||
[](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
|
[](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
|
||||||
|
|
||||||
## 目录
|
## 安装
|
||||||
|
|
||||||
- [Gitea MCP 服务器](#gitea-mcp-服务器)
|
可从 [发布页面](https://gitea.com/gitea/gitea-mcp/releases) 下载二进制文件并放入 `PATH`,或使用 `docker.gitea.com/gitea-mcp-server` 镜像,也可用 `make` 和 Go 1.26 及以上从源码构建到 `$GOPATH/bin`:
|
||||||
- [目录](#目录)
|
|
||||||
- [什么是 Gitea?](#什么是-gitea)
|
|
||||||
- [什么是 MCP?](#什么是-mcp)
|
|
||||||
- [🚧 安装](#-安装)
|
|
||||||
- [在 Claude Code 中使用](#在-claude-code-中使用)
|
|
||||||
- [在 VS Code 中使用](#在-vs-code-中使用)
|
|
||||||
- [📥 下载官方二进制版本](#-下载官方二进制版本)
|
|
||||||
- [🔧 从源码构建](#-从源码构建)
|
|
||||||
- [📁 加入 PATH](#-加入-path)
|
|
||||||
- [🚀 使用](#-使用)
|
|
||||||
- [✅ 可用工具](#-可用工具)
|
|
||||||
- [🐛 调试](#-调试)
|
|
||||||
- [🛠 疑难排解](#-疑难排解)
|
|
||||||
|
|
||||||
## 什么是 Gitea?
|
```bash
|
||||||
|
git clone https://gitea.com/gitea/gitea-mcp.git
|
||||||
|
cd gitea-mcp
|
||||||
|
make install
|
||||||
|
```
|
||||||
|
|
||||||
Gitea 是一个由社区管理的轻量级代码托管解决方案,使用 Go 语言编写,采用 MIT 许可证。Gitea 提供 Git 托管,包括仓库浏览、问题追踪、拉取请求等功能。
|
## 配置
|
||||||
|
|
||||||
## 什么是 MCP?
|
Gitea 主机和访问令牌可通过命令行参数或环境变量提供,命令行参数优先。运行 `gitea-mcp --help` 可查看完整的参数与环境变量列表。日志写入 `$HOME/.gitea-mcp/gitea-mcp.log`,加上 `-d` 可启用调试日志。
|
||||||
|
|
||||||
Model Context Protocol (MCP) 是一种协议,允许通过聊天界面整合各种工具和系统。它能够无缝执行命令并管理仓库、用户及其他资源。
|
### Claude Code
|
||||||
|
|
||||||
## 🚧 安装
|
通过 `go run` 运行服务器,需要安装 [Go](https://go.dev):
|
||||||
|
|
||||||
### 在 Claude Code 中使用
|
|
||||||
|
|
||||||
此方式使用 `go run`,需要安装 [Go](https://go.dev)。
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
claude mcp add --transport stdio --scope user gitea \
|
claude mcp add --transport stdio --scope user gitea \
|
||||||
@@ -44,15 +31,9 @@ claude mcp add --transport stdio --scope user gitea \
|
|||||||
-- go run gitea.com/gitea/gitea-mcp@latest -t stdio
|
-- go run gitea.com/gitea/gitea-mcp@latest -t stdio
|
||||||
```
|
```
|
||||||
|
|
||||||
### 在 VS Code 中使用
|
### VS Code
|
||||||
|
|
||||||
要快速安装,请使用本 README 顶部的安装按钮。
|
可使用本 README 顶部的安装按钮,或将下面的内容加入用户设置 (JSON),按 `Ctrl + Shift + P` 并输入 `Preferences: Open User Settings (JSON)` 即可打开。也可放在工作区的 `.vscode/mcp.json` 中,此时无需 `mcp` 键。
|
||||||
|
|
||||||
如需手动安装,请将以下 JSON 块添加到 VS Code 的用户设置 (JSON) 文件。可通过按 `Ctrl + Shift + P` 并输入 `Preferences: Open User Settings (JSON)`。
|
|
||||||
|
|
||||||
也可添加到工作区的 `.vscode/mcp.json` 文件,方便与他人共享配置。
|
|
||||||
|
|
||||||
> `.vscode/mcp.json` 文件不需要 `mcp` 键。
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -68,14 +49,7 @@ claude mcp add --transport stdio --scope user gitea \
|
|||||||
"servers": {
|
"servers": {
|
||||||
"gitea-mcp": {
|
"gitea-mcp": {
|
||||||
"command": "docker",
|
"command": "docker",
|
||||||
"args": [
|
"args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "docker.gitea.com/gitea-mcp-server"],
|
||||||
"run",
|
|
||||||
"-i",
|
|
||||||
"--rm",
|
|
||||||
"-e",
|
|
||||||
"GITEA_ACCESS_TOKEN",
|
|
||||||
"docker.gitea.com/gitea-mcp-server"
|
|
||||||
],
|
|
||||||
"env": {
|
"env": {
|
||||||
"GITEA_ACCESS_TOKEN": "${input:gitea_token}"
|
"GITEA_ACCESS_TOKEN": "${input:gitea_token}"
|
||||||
}
|
}
|
||||||
@@ -85,59 +59,50 @@ claude mcp add --transport stdio --scope user gitea \
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 📥 下载官方二进制版本
|
### OpenCode
|
||||||
|
|
||||||
可在 [官方 Gitea MCP 二进制版本](https://gitea.com/gitea/gitea-mcp/releases) 下载。
|
将下面的内容加入 [OpenCode](https://opencode.ai) 配置的顶层 `mcp` 对象:
|
||||||
|
|
||||||
### 🔧 从源码构建
|
```json
|
||||||
|
"gitea-mcp": {
|
||||||
可用 Git 下载源码:
|
"enabled": true,
|
||||||
|
"type": "local",
|
||||||
```bash
|
"command": [
|
||||||
git clone https://gitea.com/gitea/gitea-mcp.git
|
"gitea-mcp",
|
||||||
|
"-t", "stdio",
|
||||||
|
"-H", "https://gitea.com",
|
||||||
|
"-T", "<your personal access token>"
|
||||||
|
]
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
构建前请先安装:
|
### Mistral Vibe
|
||||||
|
|
||||||
- make
|
将下面的内容加入 `~/.vibe/config.toml`:
|
||||||
- Golang(建议 Go 1.24 及以上)
|
|
||||||
|
|
||||||
然后运行:
|
```toml
|
||||||
|
[[mcp_servers]]
|
||||||
|
name = "gitea"
|
||||||
|
transport = "stdio"
|
||||||
|
command = "docker"
|
||||||
|
args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "docker.gitea.com/gitea-mcp-server"]
|
||||||
|
|
||||||
```bash
|
[mcp_servers.env]
|
||||||
make install
|
GITEA_ACCESS_TOKEN = "TOKEN"
|
||||||
|
GITEA_HOST = "https://gitea.com"
|
||||||
```
|
```
|
||||||
|
|
||||||
### 📁 加入 PATH
|
### 其他客户端
|
||||||
|
|
||||||
安装后,将 gitea-mcp 可执行文件复制到系统 PATH 目录,例如:
|
Cursor 等客户端可使用 stdio 命令:
|
||||||
|
|
||||||
```bash
|
|
||||||
cp gitea-mcp /usr/local/bin/
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🚀 使用
|
|
||||||
|
|
||||||
此示例适用于 Cursor,也可在 VSCode 使用插件。
|
|
||||||
要配置 Gitea MCP 服务器,请将以下内容添加到 MCP 配置文件:
|
|
||||||
|
|
||||||
- **stdio 模式**
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"gitea": {
|
"gitea": {
|
||||||
"command": "gitea-mcp",
|
"command": "gitea-mcp",
|
||||||
"args": [
|
"args": ["-t", "stdio", "--host", "https://gitea.com"],
|
||||||
"-t",
|
|
||||||
"stdio",
|
|
||||||
"--host",
|
|
||||||
"https://gitea.com"
|
|
||||||
// "--token", "<your personal access token>"
|
|
||||||
],
|
|
||||||
"env": {
|
"env": {
|
||||||
// "GITEA_HOST": "https://gitea.com",
|
|
||||||
// "GITEA_INSECURE": "true",
|
|
||||||
"GITEA_ACCESS_TOKEN": "<your personal access token>"
|
"GITEA_ACCESS_TOKEN": "<your personal access token>"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,7 +110,7 @@ cp gitea-mcp /usr/local/bin/
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- **http 模式**
|
或使用 http 端点,对应以 `gitea-mcp -t http --port 8080` 启动的服务器:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -160,100 +125,74 @@ cp gitea-mcp /usr/local/bin/
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**默认日志路径**: `$HOME/.gitea-mcp/gitea-mcp.log`
|
配置完成后,可在聊天框输入 `列出我所有的仓库` 试试。
|
||||||
|
|
||||||
> [!注意]
|
## 可用工具
|
||||||
> 可通过命令行参数或环境变量提供 Gitea 主机和访问令牌。
|
|
||||||
> 命令行参数优先。
|
|
||||||
|
|
||||||
> [!注意]
|
| 工具 | 范围 | 访问 | 描述 |
|
||||||
> 许多工具支持 `page` 和 `perPage` 分页参数。最大有效页面大小由 Gitea 服务器的 `[api].MAX_RESPONSE_ITEMS` 设置决定(默认值:**50**)。请求超过此限制的 `perPage` 值将被服务器静默截断。
|
| :--------------------------- | :----------- | :- | :--------------------------------- |
|
||||||
|
| get_gitea_mcp_server_version | version | 读取 | 获取 Gitea MCP 服务器版本 |
|
||||||
|
| get_me | user | 读取 | 获取当前已认证用户 |
|
||||||
|
| get_user_orgs | user | 读取 | 列出当前用户的组织 |
|
||||||
|
| search_users | search | 读取 | 搜索用户 |
|
||||||
|
| search_org_teams | search | 读取 | 搜索组织中的团队 |
|
||||||
|
| search_repos | search | 读取 | 搜索仓库 |
|
||||||
|
| search_issues | search | 读取 | 跨仓库搜索问题和拉取请求 |
|
||||||
|
| notification_read | notification | 读取 | 读取通知:列出(可限定仓库)或按 ID 获取会话 |
|
||||||
|
| notification_write | notification | 写入 | 将某条或全部通知标记为已读 |
|
||||||
|
| label_read | label | 读取 | 读取仓库或组织标签 |
|
||||||
|
| label_write | label | 写入 | 写入标签(仓库或组织):创建、编辑、删除 |
|
||||||
|
| milestone_read | milestone | 读取 | 读取里程碑:获取单个或列出 |
|
||||||
|
| milestone_write | milestone | 写入 | 写入里程碑:创建、更新、删除 |
|
||||||
|
| wiki_read | wiki | 读取 | 读取 Wiki:列出页面、获取内容、修订历史 |
|
||||||
|
| wiki_write | wiki | 写入 | 写入 Wiki 页面:创建、更新、删除 |
|
||||||
|
| timetracking_read | timetracking | 读取 | 读取时间跟踪:问题/仓库耗时、活动计时器、我的跟踪记录 |
|
||||||
|
| timetracking_write | timetracking | 写入 | 写入时间跟踪:计时器和记录条目 |
|
||||||
|
| package_read | packages | 读取 | 读取软件包注册表:列出软件包、列出版本或获取某个版本 |
|
||||||
|
| package_write | packages | 写入 | 删除软件包版本(不可恢复) |
|
||||||
|
| list_issues | issue | 读取 | 列出仓库问题 |
|
||||||
|
| attachment_read | issue | 读取 | 读取问题/评论附件:列出元数据、获取元数据或下载内容 |
|
||||||
|
| issue_read | issue | 读取 | 读取问题:详情、评论或标签 |
|
||||||
|
| issue_write | issue | 写入 | 写入问题:创建、更新、管理评论和标签 |
|
||||||
|
| list_pull_requests | pull_request | 读取 | 列出仓库拉取请求 |
|
||||||
|
| pull_request_read | pull_request | 读取 | 读取拉取请求:详情、差异、变更文件、头部提交状态、审查 |
|
||||||
|
| pull_request_write | pull_request | 写入 | 写入拉取请求:创建、更新、关闭、重新打开、合并、更新分支、管理审查者 |
|
||||||
|
| pull_request_review_write | pull_request | 写入 | 写入 PR 审查:创建、提交、删除、驳回 |
|
||||||
|
| actions_config_read | actions | 读取 | 读取 Actions 密钥和变量 |
|
||||||
|
| actions_config_write | actions | 写入 | 写入 Actions 密钥和变量:更新插入、创建、更新、删除 |
|
||||||
|
| actions_run_read | actions | 读取 | 读取 Actions 工作流、运行、作业、日志和构件 |
|
||||||
|
| actions_run_write | actions | 写入 | 写入 Actions 运行:触发、取消、重新运行 |
|
||||||
|
| create_repo | repository | 写入 | 创建新仓库 |
|
||||||
|
| fork_repo | repository | 写入 | 复刻仓库 |
|
||||||
|
| list_my_repos | repository | 读取 | 列出当前用户拥有的仓库 |
|
||||||
|
| list_org_repos | repository | 读取 | 列出组织中的仓库 |
|
||||||
|
| get_repository_tree | repository | 读取 | 获取仓库文件树 |
|
||||||
|
| get_file_contents | file | 读取 | 获取文件内容和元数据 |
|
||||||
|
| get_dir_contents | file | 读取 | 获取目录中的条目 |
|
||||||
|
| create_or_update_file | file | 写入 | 创建或更新文件(提供 sha 以更新现有文件) |
|
||||||
|
| delete_file | file | 写入 | 删除文件 |
|
||||||
|
| create_branch | branch | 写入 | 创建新分支 |
|
||||||
|
| delete_branch | branch | 写入 | 删除分支 |
|
||||||
|
| list_branches | branch | 读取 | 列出仓库分支 |
|
||||||
|
| create_tag | tag | 写入 | 创建标签 |
|
||||||
|
| delete_tag | tag | 写入 | 删除标签 |
|
||||||
|
| get_tag | tag | 读取 | 获取标签详情 |
|
||||||
|
| list_tags | tag | 读取 | 列出仓库标签 |
|
||||||
|
| list_commits | commit | 读取 | 列出仓库提交 |
|
||||||
|
| get_commit | commit | 读取 | 获取提交详情 |
|
||||||
|
| create_release | release | 写入 | 创建版本发布 |
|
||||||
|
| delete_release | release | 写入 | 删除版本发布 |
|
||||||
|
| get_release | release | 读取 | 按 ID 获取版本发布 |
|
||||||
|
| get_latest_release | release | 读取 | 获取最新版本发布 |
|
||||||
|
| list_releases | release | 读取 | 列出仓库版本发布 |
|
||||||
|
|
||||||
一切设置完成后,可在 MCP 聊天框输入:
|
> **说明:** 部分工具是聚合的、基于操作的工具,单个工具通过 `method` 参数暴露多个操作。当服务器以只读模式运行时(`-r` / `GITEA_READONLY`),访问为「写入」的工具会被隐藏;可通过 `-S` / `--scope`(`GITEA_SCOPES`)按范围过滤,或通过 `-O` / `--tools`(`GITEA_TOOLS`)按工具名称过滤对外暴露的工具集合。
|
||||||
|
|
||||||
```text
|
未设置任一参数时,会加载所有工具;仅设置 `--scope` 时,会加载这些范围内的所有工具;仅设置 `--tools` 时,只会加载指定名称的工具;两者都设置时,会加载所选范围的工具与指定工具名称的并集。范围名称即上表「范围」列中的值,未知的范围名称仅会在启动时产生警告并被忽略。
|
||||||
列出我所有的仓库
|
|
||||||
|
```bash
|
||||||
|
gitea-mcp -S issue,pull_request
|
||||||
|
gitea-mcp --scope repository,branch --tools get_me
|
||||||
```
|
```
|
||||||
|
|
||||||
## ✅ 可用工具
|
许多工具支持 `page` 和 `per_page` 分页参数。最大有效页面大小由 Gitea 服务器的 `[api].MAX_RESPONSE_ITEMS` 设置决定(默认 **50**),超出的值会被静默截断。
|
||||||
|
|
||||||
Gitea MCP 服务器支持以下工具:
|
|
||||||
|
|
||||||
| 工具 | 范围 | 描述 |
|
|
||||||
| :-------------------------------: | :------: | :------------------------: |
|
|
||||||
| get_my_user_info | 用户 | 获取已认证用户信息 |
|
|
||||||
| get_user_orgs | 用户 | 获取已认证用户关联组织 |
|
|
||||||
| create_repo | 仓库 | 创建新仓库 |
|
|
||||||
| fork_repo | 仓库 | 复刻仓库 |
|
|
||||||
| list_my_repos | 仓库 | 列出用户所有仓库 |
|
|
||||||
| create_branch | 分支 | 创建新分支 |
|
|
||||||
| delete_branch | 分支 | 删除分支 |
|
|
||||||
| list_branches | 分支 | 列出所有分支 |
|
|
||||||
| create_release | 版本发布 | 创建新版本发布 |
|
|
||||||
| delete_release | 版本发布 | 删除版本发布 |
|
|
||||||
| get_release | 版本发布 | 获取版本发布 |
|
|
||||||
| get_latest_release | 版本发布 | 获取最新版本发布 |
|
|
||||||
| list_releases | 版本发布 | 列出所有版本发布 |
|
|
||||||
| create_tag | 标签 | 创建新标签 |
|
|
||||||
| delete_tag | 标签 | 删除标签 |
|
|
||||||
| get_tag | 标签 | 获取标签 |
|
|
||||||
| list_tags | 标签 | 列出所有标签 |
|
|
||||||
| list_repo_commits | 提交 | 列出所有提交 |
|
|
||||||
| get_file_content | 文件 | 获取文件内容和元数据 |
|
|
||||||
| get_dir_content | 文件 | 获取目录内容列表 |
|
|
||||||
| create_file | 文件 | 创建新文件 |
|
|
||||||
| update_file | 文件 | 更新现有文件 |
|
|
||||||
| delete_file | 文件 | 删除文件 |
|
|
||||||
| get_issue_by_index | 问题 | 按索引获取问题 |
|
|
||||||
| list_repo_issues | 问题 | 列出所有问题 |
|
|
||||||
| create_issue | 问题 | 创建新问题 |
|
|
||||||
| create_issue_comment | 问题 | 在问题上创建评论 |
|
|
||||||
| edit_issue | 问题 | 编辑问题 |
|
|
||||||
| edit_issue_comment | 问题 | 编辑问题评论 |
|
|
||||||
| get_issue_comments_by_index | 问题 | 按索引获取问题评论 |
|
|
||||||
| get_pull_request_by_index | 拉取请求 | 按索引获取拉取请求 |
|
|
||||||
| list_repo_pull_requests | 拉取请求 | 列出所有拉取请求 |
|
|
||||||
| create_pull_request | 拉取请求 | 创建新拉取请求 |
|
|
||||||
| create_pull_request_reviewer | 拉取请求 | 为拉取请求添加审查者 |
|
|
||||||
| delete_pull_request_reviewer | 拉取请求 | 移除拉取请求的审查者 |
|
|
||||||
| list_pull_request_reviews | 拉取请求 | 列出拉取请求的所有审查 |
|
|
||||||
| get_pull_request_review | 拉取请求 | 按 ID 获取特定审查 |
|
|
||||||
| list_pull_request_review_comments | 拉取请求 | 列出审查的行内评论 |
|
|
||||||
| create_pull_request_review | 拉取请求 | 创建审查(可含行内评论) |
|
|
||||||
| submit_pull_request_review | 拉取请求 | 提交待处理的审查 |
|
|
||||||
| delete_pull_request_review | 拉取请求 | 删除审查 |
|
|
||||||
| dismiss_pull_request_review | 拉取请求 | 驳回审查(可附消息) |
|
|
||||||
| merge_pull_request | 拉取请求 | 合并拉取请求 |
|
|
||||||
| search_users | 用户 | 搜索用户 |
|
|
||||||
| search_org_teams | 组织 | 搜索组织团队 |
|
|
||||||
| list_org_labels | 组织 | 列出组织标签 |
|
|
||||||
| create_org_label | 组织 | 创建组织标签 |
|
|
||||||
| edit_org_label | 组织 | 编辑组织标签 |
|
|
||||||
| delete_org_label | 组织 | 删除组织标签 |
|
|
||||||
| search_repos | 仓库 | 搜索仓库 |
|
|
||||||
| get_gitea_mcp_server_version | 服务器 | 获取 Gitea MCP 服务器版本 |
|
|
||||||
| list_wiki_pages | Wiki | 列出所有 Wiki 页面 |
|
|
||||||
| get_wiki_page | Wiki | 获取 Wiki 页面内容和元数据 |
|
|
||||||
| get_wiki_revisions | Wiki | 获取 Wiki 修订历史 |
|
|
||||||
| create_wiki_page | Wiki | 创建新 Wiki 页面 |
|
|
||||||
| update_wiki_page | Wiki | 更新现有 Wiki 页面 |
|
|
||||||
| delete_wiki_page | Wiki | 删除 Wiki 页面 |
|
|
||||||
|
|
||||||
## 🐛 调试
|
|
||||||
|
|
||||||
启用调试模式时,请在 http 模式运行 Gitea MCP 服务器时加上 `-d` 标志:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
./gitea-mcp -t http [--port 8080] --token <your personal access token> -d
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🛠 疑难排解
|
|
||||||
|
|
||||||
如遇问题,可参考以下步骤:
|
|
||||||
|
|
||||||
1. **检查 PATH**:确保 `gitea-mcp` 可执行文件已在系统 PATH 目录中。
|
|
||||||
2. **验证依赖**:确认已安装 `make` 和 `Golang` 等必要依赖。
|
|
||||||
3. **检查配置**:仔细检查 MCP 配置文件是否有错误或遗漏。
|
|
||||||
4. **查看日志**:检查日志消息或警告以获取更多信息。
|
|
||||||
|
|
||||||
享受通过聊天探索和管理您的 Gitea 仓库!
|
|
||||||
|
|||||||
+108
-169
@@ -2,40 +2,27 @@
|
|||||||
|
|
||||||
[English](README.md) | [简体中文](README.zh-cn.md)
|
[English](README.md) | [简体中文](README.zh-cn.md)
|
||||||
|
|
||||||
**Gitea MCP 伺服器** 是一個整合插件,旨在將 Gitea 與 Model Context Protocol (MCP) 系統連接起來。這允許通過 MCP 兼容的聊天界面無縫執行命令和管理倉庫。
|
**Gitea MCP 伺服器** 將 [Gitea](https://about.gitea.com) 實例接入 [Model Context Protocol](https://modelcontextprotocol.io) 客戶端,讓倉庫、問題、拉取請求等都能在相容 MCP 的聊天介面中瀏覽與管理。
|
||||||
|
|
||||||
[](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
|
[](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
|
||||||
|
|
||||||
## 目錄
|
## 安裝
|
||||||
|
|
||||||
- [Gitea MCP 伺服器](#gitea-mcp-伺服器)
|
可從 [發布頁面](https://gitea.com/gitea/gitea-mcp/releases) 下載二進位檔並放入 `PATH`,或使用 `docker.gitea.com/gitea-mcp-server` 映像檔,也可用 `make` 與 Go 1.26 以上從原始碼建置到 `$GOPATH/bin`:
|
||||||
- [目錄](#目錄)
|
|
||||||
- [什麼是 Gitea?](#什麼是-gitea)
|
|
||||||
- [什麼是 MCP?](#什麼是-mcp)
|
|
||||||
- [🚧 安裝](#-安裝)
|
|
||||||
- [在 Claude Code 中使用](#在-claude-code-中使用)
|
|
||||||
- [在 VS Code 中使用](#在-vs-code-中使用)
|
|
||||||
- [📥 下載官方二進位版本](#-下載官方二進位版本)
|
|
||||||
- [🔧 從原始碼建置](#-從原始碼建置)
|
|
||||||
- [📁 加入 PATH](#-加入-path)
|
|
||||||
- [🚀 使用](#-使用)
|
|
||||||
- [✅ 可用工具](#-可用工具)
|
|
||||||
- [🐛 調試](#-調試)
|
|
||||||
- [🛠 疑難排解](#-疑難排解)
|
|
||||||
|
|
||||||
## 什麼是 Gitea?
|
```bash
|
||||||
|
git clone https://gitea.com/gitea/gitea-mcp.git
|
||||||
|
cd gitea-mcp
|
||||||
|
make install
|
||||||
|
```
|
||||||
|
|
||||||
Gitea 是一個由社群管理的輕量級程式碼託管解決方案,使用 Go 語言編寫,採用 MIT 授權。Gitea 提供 Git 託管,包括倉庫瀏覽、議題追蹤、拉取請求等功能。
|
## 設定
|
||||||
|
|
||||||
## 什麼是 MCP?
|
Gitea 主機與存取令牌可透過命令列參數或環境變數提供,命令列參數優先。執行 `gitea-mcp --help` 可查看完整的參數與環境變數列表。日誌寫入 `$HOME/.gitea-mcp/gitea-mcp.log`,加上 `-d` 可啟用除錯日誌。
|
||||||
|
|
||||||
Model Context Protocol (MCP) 是一種協議,允許透過聊天介面整合各種工具與系統。它能夠無縫執行命令並管理倉庫、使用者及其他資源。
|
### Claude Code
|
||||||
|
|
||||||
## 🚧 安裝
|
透過 `go run` 執行伺服器,需要安裝 [Go](https://go.dev):
|
||||||
|
|
||||||
### 在 Claude Code 中使用
|
|
||||||
|
|
||||||
此方式使用 `go run`,需要安裝 [Go](https://go.dev)。
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
claude mcp add --transport stdio --scope user gitea \
|
claude mcp add --transport stdio --scope user gitea \
|
||||||
@@ -44,15 +31,9 @@ claude mcp add --transport stdio --scope user gitea \
|
|||||||
-- go run gitea.com/gitea/gitea-mcp@latest -t stdio
|
-- go run gitea.com/gitea/gitea-mcp@latest -t stdio
|
||||||
```
|
```
|
||||||
|
|
||||||
### 在 VS Code 中使用
|
### VS Code
|
||||||
|
|
||||||
欲快速安裝,請使用本 README 頂部的安裝按鈕。
|
可使用本 README 頂部的安裝按鈕,或將下面的內容加入使用者設定 (JSON),按 `Ctrl + Shift + P` 並輸入 `Preferences: Open User Settings (JSON)` 即可開啟。也可放在工作區的 `.vscode/mcp.json` 中,此時不需要 `mcp` 鍵。
|
||||||
|
|
||||||
如需手動安裝,請將下列 JSON 區塊加入 VS Code 的使用者設定 (JSON) 檔案。可按 `Ctrl + Shift + P` 並輸入 `Preferences: Open User Settings (JSON)`。
|
|
||||||
|
|
||||||
也可加入至工作區的 `.vscode/mcp.json` 檔案,方便與他人共享設定。
|
|
||||||
|
|
||||||
> `.vscode/mcp.json` 檔案不需 `mcp` 鍵。
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -68,14 +49,7 @@ claude mcp add --transport stdio --scope user gitea \
|
|||||||
"servers": {
|
"servers": {
|
||||||
"gitea-mcp": {
|
"gitea-mcp": {
|
||||||
"command": "docker",
|
"command": "docker",
|
||||||
"args": [
|
"args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "docker.gitea.com/gitea-mcp-server"],
|
||||||
"run",
|
|
||||||
"-i",
|
|
||||||
"--rm",
|
|
||||||
"-e",
|
|
||||||
"GITEA_ACCESS_TOKEN",
|
|
||||||
"docker.gitea.com/gitea-mcp-server"
|
|
||||||
],
|
|
||||||
"env": {
|
"env": {
|
||||||
"GITEA_ACCESS_TOKEN": "${input:gitea_token}"
|
"GITEA_ACCESS_TOKEN": "${input:gitea_token}"
|
||||||
}
|
}
|
||||||
@@ -85,59 +59,50 @@ claude mcp add --transport stdio --scope user gitea \
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 📥 下載官方二進位版本
|
### OpenCode
|
||||||
|
|
||||||
可至 [官方 Gitea MCP 二進位版本](https://gitea.com/gitea/gitea-mcp/releases) 下載。
|
將下面的內容加入 [OpenCode](https://opencode.ai) 設定的頂層 `mcp` 物件:
|
||||||
|
|
||||||
### 🔧 從原始碼建置
|
```json
|
||||||
|
"gitea-mcp": {
|
||||||
可用 Git 下載原始碼:
|
"enabled": true,
|
||||||
|
"type": "local",
|
||||||
```bash
|
"command": [
|
||||||
git clone https://gitea.com/gitea/gitea-mcp.git
|
"gitea-mcp",
|
||||||
|
"-t", "stdio",
|
||||||
|
"-H", "https://gitea.com",
|
||||||
|
"-T", "<your personal access token>"
|
||||||
|
]
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
建置前請先安裝:
|
### Mistral Vibe
|
||||||
|
|
||||||
- make
|
將下面的內容加入 `~/.vibe/config.toml`:
|
||||||
- Golang(建議 Go 1.24 以上)
|
|
||||||
|
|
||||||
然後執行:
|
```toml
|
||||||
|
[[mcp_servers]]
|
||||||
|
name = "gitea"
|
||||||
|
transport = "stdio"
|
||||||
|
command = "docker"
|
||||||
|
args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "docker.gitea.com/gitea-mcp-server"]
|
||||||
|
|
||||||
```bash
|
[mcp_servers.env]
|
||||||
make install
|
GITEA_ACCESS_TOKEN = "TOKEN"
|
||||||
|
GITEA_HOST = "https://gitea.com"
|
||||||
```
|
```
|
||||||
|
|
||||||
### 📁 加入 PATH
|
### 其他客戶端
|
||||||
|
|
||||||
安裝後,將 gitea-mcp 執行檔複製到系統 PATH 目錄,例如:
|
Cursor 等客戶端可使用 stdio 命令:
|
||||||
|
|
||||||
```bash
|
|
||||||
cp gitea-mcp /usr/local/bin/
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🚀 使用
|
|
||||||
|
|
||||||
此範例適用於 Cursor,也可在 VSCode 使用插件。
|
|
||||||
欲設定 Gitea MCP 伺服器,請將下列內容加入 MCP 設定檔:
|
|
||||||
|
|
||||||
- **stdio 模式**
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"gitea": {
|
"gitea": {
|
||||||
"command": "gitea-mcp",
|
"command": "gitea-mcp",
|
||||||
"args": [
|
"args": ["-t", "stdio", "--host", "https://gitea.com"],
|
||||||
"-t",
|
|
||||||
"stdio",
|
|
||||||
"--host",
|
|
||||||
"https://gitea.com"
|
|
||||||
// "--token", "<your personal access token>"
|
|
||||||
],
|
|
||||||
"env": {
|
"env": {
|
||||||
// "GITEA_HOST": "https://gitea.com",
|
|
||||||
// "GITEA_INSECURE": "true",
|
|
||||||
"GITEA_ACCESS_TOKEN": "<your personal access token>"
|
"GITEA_ACCESS_TOKEN": "<your personal access token>"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,7 +110,7 @@ cp gitea-mcp /usr/local/bin/
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- **http 模式**
|
或使用 http 端點,對應以 `gitea-mcp -t http --port 8080` 啟動的伺服器:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -160,100 +125,74 @@ cp gitea-mcp /usr/local/bin/
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**預設日誌路徑**: `$HOME/.gitea-mcp/gitea-mcp.log`
|
設定完成後,可在聊天框輸入 `列出我所有的倉庫` 試試。
|
||||||
|
|
||||||
> [!注意]
|
## 可用工具
|
||||||
> 可用命令列參數或環境變數提供 Gitea 主機與存取令牌。
|
|
||||||
> 命令列參數優先。
|
|
||||||
|
|
||||||
> [!注意]
|
| 工具 | 範圍 | 存取 | 描述 |
|
||||||
> 許多工具支援 `page` 和 `perPage` 分頁參數。最大有效頁面大小由 Gitea 伺服器的 `[api].MAX_RESPONSE_ITEMS` 設定決定(預設值:**50**)。請求超過此限制的 `perPage` 值將被伺服器靜默截斷。
|
| :--------------------------- | :----------- | :- | :--------------------------------- |
|
||||||
|
| get_gitea_mcp_server_version | version | 讀取 | 取得 Gitea MCP 伺服器版本 |
|
||||||
|
| get_me | user | 讀取 | 取得目前已認證用戶 |
|
||||||
|
| get_user_orgs | user | 讀取 | 列出目前用戶的組織 |
|
||||||
|
| search_users | search | 讀取 | 搜尋用戶 |
|
||||||
|
| search_org_teams | search | 讀取 | 搜尋組織中的團隊 |
|
||||||
|
| search_repos | search | 讀取 | 搜尋倉庫 |
|
||||||
|
| search_issues | search | 讀取 | 跨倉庫搜尋問題和拉取請求 |
|
||||||
|
| notification_read | notification | 讀取 | 讀取通知:列出(可限定倉庫)或依 ID 取得會話 |
|
||||||
|
| notification_write | notification | 寫入 | 將某條或全部通知標記為已讀 |
|
||||||
|
| label_read | label | 讀取 | 讀取倉庫或組織標籤 |
|
||||||
|
| label_write | label | 寫入 | 寫入標籤(倉庫或組織):創建、編輯、刪除 |
|
||||||
|
| milestone_read | milestone | 讀取 | 讀取里程碑:取得單個或列出 |
|
||||||
|
| milestone_write | milestone | 寫入 | 寫入里程碑:創建、更新、刪除 |
|
||||||
|
| wiki_read | wiki | 讀取 | 讀取 Wiki:列出頁面、取得內容、修訂歷史 |
|
||||||
|
| wiki_write | wiki | 寫入 | 寫入 Wiki 頁面:創建、更新、刪除 |
|
||||||
|
| timetracking_read | timetracking | 讀取 | 讀取時間追蹤:問題/倉庫耗時、活動計時器、我的追蹤記錄 |
|
||||||
|
| timetracking_write | timetracking | 寫入 | 寫入時間追蹤:計時器和記錄項目 |
|
||||||
|
| package_read | packages | 讀取 | 讀取軟體套件註冊表:列出套件、列出版本或取得某個版本 |
|
||||||
|
| package_write | packages | 寫入 | 刪除軟體套件版本(不可復原) |
|
||||||
|
| list_issues | issue | 讀取 | 列出倉庫問題 |
|
||||||
|
| attachment_read | issue | 讀取 | 讀取問題/評論附件:列出中繼資料、取得中繼資料或下載內容 |
|
||||||
|
| issue_read | issue | 讀取 | 讀取問題:詳情、評論或標籤 |
|
||||||
|
| issue_write | issue | 寫入 | 寫入問題:創建、更新、管理評論和標籤 |
|
||||||
|
| list_pull_requests | pull_request | 讀取 | 列出倉庫拉取請求 |
|
||||||
|
| pull_request_read | pull_request | 讀取 | 讀取拉取請求:詳情、差異、變更檔案、頭部提交狀態、審查 |
|
||||||
|
| pull_request_write | pull_request | 寫入 | 寫入拉取請求:創建、更新、關閉、重新開啟、合併、更新分支、管理審查者 |
|
||||||
|
| pull_request_review_write | pull_request | 寫入 | 寫入 PR 審查:創建、提交、刪除、駁回 |
|
||||||
|
| actions_config_read | actions | 讀取 | 讀取 Actions 密鑰和變數 |
|
||||||
|
| actions_config_write | actions | 寫入 | 寫入 Actions 密鑰和變數:更新插入、創建、更新、刪除 |
|
||||||
|
| actions_run_read | actions | 讀取 | 讀取 Actions 工作流程、執行、作業、日誌和產物 |
|
||||||
|
| actions_run_write | actions | 寫入 | 寫入 Actions 執行:觸發、取消、重新執行 |
|
||||||
|
| create_repo | repository | 寫入 | 創建新倉庫 |
|
||||||
|
| fork_repo | repository | 寫入 | 復刻倉庫 |
|
||||||
|
| list_my_repos | repository | 讀取 | 列出目前用戶擁有的倉庫 |
|
||||||
|
| list_org_repos | repository | 讀取 | 列出組織中的倉庫 |
|
||||||
|
| get_repository_tree | repository | 讀取 | 取得倉庫檔案樹 |
|
||||||
|
| get_file_contents | file | 讀取 | 取得檔案內容與中繼資料 |
|
||||||
|
| get_dir_contents | file | 讀取 | 取得目錄中的項目 |
|
||||||
|
| create_or_update_file | file | 寫入 | 創建或更新檔案(提供 sha 以更新現有檔案) |
|
||||||
|
| delete_file | file | 寫入 | 刪除檔案 |
|
||||||
|
| create_branch | branch | 寫入 | 創建新分支 |
|
||||||
|
| delete_branch | branch | 寫入 | 刪除分支 |
|
||||||
|
| list_branches | branch | 讀取 | 列出倉庫分支 |
|
||||||
|
| create_tag | tag | 寫入 | 創建標籤 |
|
||||||
|
| delete_tag | tag | 寫入 | 刪除標籤 |
|
||||||
|
| get_tag | tag | 讀取 | 取得標籤詳情 |
|
||||||
|
| list_tags | tag | 讀取 | 列出倉庫標籤 |
|
||||||
|
| list_commits | commit | 讀取 | 列出倉庫提交 |
|
||||||
|
| get_commit | commit | 讀取 | 取得提交詳情 |
|
||||||
|
| create_release | release | 寫入 | 創建版本發布 |
|
||||||
|
| delete_release | release | 寫入 | 刪除版本發布 |
|
||||||
|
| get_release | release | 讀取 | 依 ID 取得版本發布 |
|
||||||
|
| get_latest_release | release | 讀取 | 取得最新版本發布 |
|
||||||
|
| list_releases | release | 讀取 | 列出倉庫版本發布 |
|
||||||
|
|
||||||
一切設定完成後,可在 MCP 聊天框輸入:
|
> **說明:** 部分工具是聚合的、基於操作的工具,單個工具透過 `method` 參數暴露多個操作。當伺服器以唯讀模式執行時(`-r` / `GITEA_READONLY`),存取為「寫入」的工具會被隱藏;可透過 `-S` / `--scope`(`GITEA_SCOPES`)依範圍過濾,或透過 `-O` / `--tools`(`GITEA_TOOLS`)依工具名稱過濾對外暴露的工具集合。
|
||||||
|
|
||||||
```text
|
未設定任一參數時,會載入所有工具;僅設定 `--scope` 時,會載入這些範圍內的所有工具;僅設定 `--tools` 時,只會載入指定名稱的工具;兩者皆設定時,會載入所選範圍的工具與指定工具名稱的聯集。範圍名稱即上表「範圍」欄中的值,未知的範圍名稱僅會在啟動時發出警告並被忽略。
|
||||||
列出我所有的倉庫
|
|
||||||
|
```bash
|
||||||
|
gitea-mcp -S issue,pull_request
|
||||||
|
gitea-mcp --scope repository,branch --tools get_me
|
||||||
```
|
```
|
||||||
|
|
||||||
## ✅ 可用工具
|
許多工具支援 `page` 和 `per_page` 分頁參數。最大有效頁面大小由 Gitea 伺服器的 `[api].MAX_RESPONSE_ITEMS` 設定決定(預設 **50**),超出的值會被靜默截斷。
|
||||||
|
|
||||||
Gitea MCP 伺服器支援以下工具:
|
|
||||||
|
|
||||||
| 工具 | 範圍 | 描述 |
|
|
||||||
| :-------------------------------: | :------: | :--------------------------: |
|
|
||||||
| get_my_user_info | 用戶 | 取得已認證用戶資訊 |
|
|
||||||
| get_user_orgs | 用戶 | 取得已認證用戶所屬組織 |
|
|
||||||
| create_repo | 倉庫 | 創建新倉庫 |
|
|
||||||
| fork_repo | 倉庫 | 復刻倉庫 |
|
|
||||||
| list_my_repos | 倉庫 | 列出用戶所有倉庫 |
|
|
||||||
| create_branch | 分支 | 創建新分支 |
|
|
||||||
| delete_branch | 分支 | 刪除分支 |
|
|
||||||
| list_branches | 分支 | 列出所有分支 |
|
|
||||||
| create_release | 版本發布 | 創建新版本發布 |
|
|
||||||
| delete_release | 版本發布 | 刪除版本發布 |
|
|
||||||
| get_release | 版本發布 | 取得版本發布 |
|
|
||||||
| get_latest_release | 版本發布 | 取得最新版本發布 |
|
|
||||||
| list_releases | 版本發布 | 列出所有版本發布 |
|
|
||||||
| create_tag | 標籤 | 創建新標籤 |
|
|
||||||
| delete_tag | 標籤 | 刪除標籤 |
|
|
||||||
| get_tag | 標籤 | 取得標籤 |
|
|
||||||
| list_tags | 標籤 | 列出所有標籤 |
|
|
||||||
| list_repo_commits | 提交 | 列出所有提交 |
|
|
||||||
| get_file_content | 文件 | 取得文件內容與中繼資料 |
|
|
||||||
| get_dir_content | 文件 | 取得目錄內容列表 |
|
|
||||||
| create_file | 文件 | 創建新文件 |
|
|
||||||
| update_file | 文件 | 更新現有文件 |
|
|
||||||
| delete_file | 文件 | 刪除文件 |
|
|
||||||
| get_issue_by_index | 問題 | 依索引取得問題 |
|
|
||||||
| list_repo_issues | 問題 | 列出所有問題 |
|
|
||||||
| create_issue | 問題 | 創建新問題 |
|
|
||||||
| create_issue_comment | 問題 | 在問題上創建評論 |
|
|
||||||
| edit_issue | 問題 | 編輯問題 |
|
|
||||||
| edit_issue_comment | 問題 | 編輯問題評論 |
|
|
||||||
| get_issue_comments_by_index | 問題 | 依索引取得問題評論 |
|
|
||||||
| get_pull_request_by_index | 拉取請求 | 依索引取得拉取請求 |
|
|
||||||
| list_repo_pull_requests | 拉取請求 | 列出所有拉取請求 |
|
|
||||||
| create_pull_request | 拉取請求 | 創建新拉取請求 |
|
|
||||||
| create_pull_request_reviewer | 拉取請求 | 為拉取請求添加審查者 |
|
|
||||||
| delete_pull_request_reviewer | 拉取請求 | 移除拉取請求的審查者 |
|
|
||||||
| list_pull_request_reviews | 拉取請求 | 列出拉取請求的所有審查 |
|
|
||||||
| get_pull_request_review | 拉取請求 | 依 ID 取得特定審查 |
|
|
||||||
| list_pull_request_review_comments | 拉取請求 | 列出審查的行內評論 |
|
|
||||||
| create_pull_request_review | 拉取請求 | 創建審查(可含行內評論) |
|
|
||||||
| submit_pull_request_review | 拉取請求 | 提交待處理的審查 |
|
|
||||||
| delete_pull_request_review | 拉取請求 | 刪除審查 |
|
|
||||||
| dismiss_pull_request_review | 拉取請求 | 駁回審查(可附訊息) |
|
|
||||||
| merge_pull_request | 拉取請求 | 合併拉取請求 |
|
|
||||||
| search_users | 用戶 | 搜尋用戶 |
|
|
||||||
| search_org_teams | 組織 | 搜尋組織團隊 |
|
|
||||||
| list_org_labels | 組織 | 列出組織標籤 |
|
|
||||||
| create_org_label | 組織 | 創建組織標籤 |
|
|
||||||
| edit_org_label | 組織 | 編輯組織標籤 |
|
|
||||||
| delete_org_label | 組織 | 刪除組織標籤 |
|
|
||||||
| search_repos | 倉庫 | 搜尋倉庫 |
|
|
||||||
| get_gitea_mcp_server_version | 伺服器 | 取得 Gitea MCP 伺服器版本 |
|
|
||||||
| list_wiki_pages | Wiki | 列出所有 Wiki 頁面 |
|
|
||||||
| get_wiki_page | Wiki | 取得 Wiki 頁面內容與中繼資料 |
|
|
||||||
| get_wiki_revisions | Wiki | 取得 Wiki 修訂歷史 |
|
|
||||||
| create_wiki_page | Wiki | 創建新 Wiki 頁面 |
|
|
||||||
| update_wiki_page | Wiki | 更新現有 Wiki 頁面 |
|
|
||||||
| delete_wiki_page | Wiki | 刪除 Wiki 頁面 |
|
|
||||||
|
|
||||||
## 🐛 調試
|
|
||||||
|
|
||||||
啟用調試模式時,請在 http 模式執行 Gitea MCP 伺服器時加上 `-d` 旗標:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
./gitea-mcp -t http [--port 8080] --token <your personal access token> -d
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🛠 疑難排解
|
|
||||||
|
|
||||||
如遇問題,可參考以下步驟:
|
|
||||||
|
|
||||||
1. **檢查 PATH**:確保 `gitea-mcp` 執行檔已在系統 PATH 目錄中。
|
|
||||||
2. **驗證依賴**:確認已安裝 `make` 與 `Golang` 等必要依賴。
|
|
||||||
3. **檢查設定**:仔細檢查 MCP 設定檔是否有錯誤或遺漏。
|
|
||||||
4. **查看日誌**:檢查日誌訊息或警告以獲取更多資訊。
|
|
||||||
|
|
||||||
享受透過聊天探索與管理您的 Gitea 倉庫!
|
|
||||||
|
|||||||
+101
-47
@@ -4,7 +4,9 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
|
|
||||||
@@ -14,47 +16,66 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
host string
|
host string
|
||||||
port int
|
port int
|
||||||
token string
|
token string
|
||||||
tools string
|
tools string
|
||||||
version bool
|
scopes string
|
||||||
|
version bool
|
||||||
|
maxInlineAttachmentBytes int
|
||||||
|
maxInlineAttachmentBytesFlagSet bool
|
||||||
|
osExit = os.Exit
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, readFile func(string) ([]byte, error), stderr io.Writer) {
|
||||||
flag.StringVar(&flagPkg.Mode, "t", "stdio", "")
|
fs.StringVar(&flagPkg.Mode, "t", "stdio", "")
|
||||||
flag.StringVar(&flagPkg.Mode, "transport", "stdio", "")
|
fs.StringVar(&flagPkg.Mode, "transport", "stdio", "")
|
||||||
flag.StringVar(&host, "H", os.Getenv("GITEA_HOST"), "")
|
fs.StringVar(&host, "H", getenv("GITEA_HOST"), "")
|
||||||
flag.StringVar(&host, "host", os.Getenv("GITEA_HOST"), "")
|
fs.StringVar(&host, "host", getenv("GITEA_HOST"), "")
|
||||||
flag.IntVar(&port, "p", 8080, "")
|
fs.IntVar(&port, "p", 8080, "")
|
||||||
flag.IntVar(&port, "port", 8080, "")
|
fs.IntVar(&port, "port", 8080, "")
|
||||||
flag.StringVar(&token, "T", "", "")
|
fs.StringVar(&token, "T", "", "")
|
||||||
flag.StringVar(&token, "token", "", "")
|
fs.StringVar(&token, "token", "", "")
|
||||||
flag.BoolVar(&flagPkg.ReadOnly, "r", false, "")
|
fs.BoolVar(&flagPkg.ReadOnly, "r", false, "")
|
||||||
flag.BoolVar(&flagPkg.ReadOnly, "read-only", false, "")
|
fs.BoolVar(&flagPkg.ReadOnly, "read-only", false, "")
|
||||||
defaultTools := os.Getenv("GITEA_TOOLS")
|
defaultTools := getenv("GITEA_TOOLS")
|
||||||
flag.StringVar(&tools, "O", defaultTools, "")
|
fs.StringVar(&tools, "O", defaultTools, "")
|
||||||
flag.StringVar(&tools, "tools", defaultTools, "")
|
fs.StringVar(&tools, "tools", defaultTools, "")
|
||||||
flag.BoolVar(&flagPkg.Debug, "d", false, "")
|
defaultScopes := getenv("GITEA_SCOPES")
|
||||||
flag.BoolVar(&flagPkg.Debug, "debug", false, "")
|
fs.StringVar(&scopes, "S", defaultScopes, "")
|
||||||
flag.BoolVar(&flagPkg.Insecure, "k", false, "")
|
fs.StringVar(&scopes, "scope", defaultScopes, "")
|
||||||
flag.BoolVar(&flagPkg.Insecure, "insecure", false, "")
|
fs.BoolVar(&flagPkg.Debug, "d", false, "")
|
||||||
flag.BoolVar(&version, "v", false, "")
|
fs.BoolVar(&flagPkg.Debug, "debug", false, "")
|
||||||
flag.BoolVar(&version, "version", false, "")
|
fs.BoolVar(&flagPkg.Insecure, "k", false, "")
|
||||||
|
fs.BoolVar(&flagPkg.Insecure, "insecure", false, "")
|
||||||
|
fs.BoolVar(&version, "v", false, "")
|
||||||
|
fs.BoolVar(&version, "version", false, "")
|
||||||
|
maxInlineAttachmentBytes = 5 * 1024 * 1024
|
||||||
|
fs.Func("max-inline-attachment-bytes", "", func(val string) error {
|
||||||
|
parsed, err := strconv.Atoi(val)
|
||||||
|
if err != nil || parsed < 0 {
|
||||||
|
return fmt.Errorf("invalid value %q", val)
|
||||||
|
}
|
||||||
|
maxInlineAttachmentBytes = parsed
|
||||||
|
maxInlineAttachmentBytesFlagSet = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
flag.Usage = func() {
|
fs.Usage = func() {
|
||||||
w := tabwriter.NewWriter(os.Stderr, 0, 0, 3, ' ', 0)
|
w := tabwriter.NewWriter(stderr, 0, 0, 3, ' ', 0)
|
||||||
fmt.Fprintln(os.Stderr, "Usage: gitea-mcp [options]")
|
fmt.Fprintln(stderr, "Usage: gitea-mcp [options]")
|
||||||
fmt.Fprintln(os.Stderr)
|
fmt.Fprintln(stderr)
|
||||||
fmt.Fprintln(os.Stderr, "Options:")
|
fmt.Fprintln(stderr, "Options:")
|
||||||
fmt.Fprintf(w, " -t, -transport <type>\tTransport type: stdio or http (default: stdio)\n")
|
fmt.Fprintf(w, " -t, -transport <type>\tTransport type: stdio or http (default: stdio)\n")
|
||||||
fmt.Fprintf(w, " -H, -host <url>\tGitea host URL (default: https://gitea.com)\n")
|
fmt.Fprintf(w, " -H, -host <url>\tGitea host URL (default: https://gitea.com)\n")
|
||||||
fmt.Fprintf(w, " -p, -port <number>\tHTTP server port (default: 8080)\n")
|
fmt.Fprintf(w, " -p, -port <number>\tHTTP server port (default: 8080)\n")
|
||||||
fmt.Fprintf(w, " -T, -token <token>\tPersonal access token\n")
|
fmt.Fprintf(w, " -T, -token <token>\tPersonal access token\n")
|
||||||
fmt.Fprintf(w, " -r, -read-only\tExpose only read-only tools\n")
|
fmt.Fprintf(w, " -r, -read-only\tExpose only read-only tools\n")
|
||||||
fmt.Fprintf(w, " -O, -tools <names>\tComma-separated list of tool names to expose\n")
|
fmt.Fprintf(w, " -O, -tools <names>\tComma-separated list of tool names to expose\n")
|
||||||
|
fmt.Fprintf(w, " -S, -scope <names>\tComma-separated list of tool scopes to expose\n")
|
||||||
fmt.Fprintf(w, " -d, -debug\tEnable debug mode\n")
|
fmt.Fprintf(w, " -d, -debug\tEnable debug mode\n")
|
||||||
fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n")
|
fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n")
|
||||||
|
fmt.Fprintf(w, " -max-inline-attachment-bytes <bytes>\tInline image attachments up to this size (default: 5242880)\n")
|
||||||
fmt.Fprintf(w, " -v, -version\tPrint version and exit\n")
|
fmt.Fprintf(w, " -v, -version\tPrint version and exit\n")
|
||||||
fmt.Fprintln(w)
|
fmt.Fprintln(w)
|
||||||
fmt.Fprintln(w, "Environment variables:")
|
fmt.Fprintln(w, "Environment variables:")
|
||||||
@@ -63,13 +84,15 @@ func init() {
|
|||||||
fmt.Fprintf(w, " GITEA_DEBUG\tSet to 'true' for debug mode\n")
|
fmt.Fprintf(w, " GITEA_DEBUG\tSet to 'true' for debug mode\n")
|
||||||
fmt.Fprintf(w, " GITEA_HOST\tOverride Gitea host URL\n")
|
fmt.Fprintf(w, " GITEA_HOST\tOverride Gitea host URL\n")
|
||||||
fmt.Fprintf(w, " GITEA_INSECURE\tSet to 'true' to ignore TLS errors\n")
|
fmt.Fprintf(w, " GITEA_INSECURE\tSet to 'true' to ignore TLS errors\n")
|
||||||
|
fmt.Fprintf(w, " GITEA_MAX_INLINE_ATTACHMENT_BYTES\tOverride inline image attachment size limit in bytes\n")
|
||||||
fmt.Fprintf(w, " GITEA_READONLY\tSet to 'true' for read-only mode\n")
|
fmt.Fprintf(w, " GITEA_READONLY\tSet to 'true' for read-only mode\n")
|
||||||
|
fmt.Fprintf(w, " GITEA_SCOPES\tComma-separated list of tool scopes to expose\n")
|
||||||
fmt.Fprintf(w, " GITEA_TOOLS\tComma-separated list of tool names to expose\n")
|
fmt.Fprintf(w, " GITEA_TOOLS\tComma-separated list of tool names to expose\n")
|
||||||
fmt.Fprintf(w, " MCP_MODE\tOverride transport mode\n")
|
fmt.Fprintf(w, " MCP_MODE\tOverride transport mode\n")
|
||||||
w.Flush()
|
_ = w.Flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
flag.Parse()
|
_ = fs.Parse(args)
|
||||||
|
|
||||||
flagPkg.Host = host
|
flagPkg.Host = host
|
||||||
if flagPkg.Host == "" {
|
if flagPkg.Host == "" {
|
||||||
@@ -77,27 +100,27 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
flagPkg.Port = port
|
flagPkg.Port = port
|
||||||
|
flagPkg.MaxInlineAttachmentBytes = maxInlineAttachmentBytes
|
||||||
|
|
||||||
flagPkg.Token = token
|
flagPkg.Token = token
|
||||||
if flagPkg.Token == "" {
|
if flagPkg.Token == "" {
|
||||||
flagPkg.Token = os.Getenv("GITEA_ACCESS_TOKEN")
|
flagPkg.Token = getenv("GITEA_ACCESS_TOKEN")
|
||||||
}
|
}
|
||||||
if flagPkg.Token == "" {
|
if flagPkg.Token == "" {
|
||||||
if tokenFile := os.Getenv("GITEA_ACCESS_TOKEN_FILE"); tokenFile != "" {
|
if tokenFile := getenv("GITEA_ACCESS_TOKEN_FILE"); tokenFile != "" {
|
||||||
data, err := os.ReadFile(tokenFile)
|
data, err := readFile(tokenFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "error reading GITEA_ACCESS_TOKEN_FILE: %v\n", err)
|
fmt.Fprintf(stderr, "error reading GITEA_ACCESS_TOKEN_FILE: %v\n", err)
|
||||||
os.Exit(1)
|
osExit(1)
|
||||||
}
|
}
|
||||||
flagPkg.Token = strings.TrimRight(string(data), "\r\n")
|
flagPkg.Token = strings.TrimRight(string(data), "\r\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if os.Getenv("MCP_MODE") != "" {
|
if getenv("MCP_MODE") != "" {
|
||||||
flagPkg.Mode = os.Getenv("MCP_MODE")
|
flagPkg.Mode = getenv("MCP_MODE")
|
||||||
}
|
}
|
||||||
|
if getenv("GITEA_READONLY") == "true" {
|
||||||
if os.Getenv("GITEA_READONLY") == "true" {
|
|
||||||
flagPkg.ReadOnly = true
|
flagPkg.ReadOnly = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,27 +134,58 @@ func init() {
|
|||||||
flagPkg.AllowedTools = allowed
|
flagPkg.AllowedTools = allowed
|
||||||
}
|
}
|
||||||
|
|
||||||
if os.Getenv("GITEA_DEBUG") == "true" {
|
allowedScopes := map[string]struct{}{}
|
||||||
|
for s := range strings.SplitSeq(scopes, ",") {
|
||||||
|
if s = normalizeScope(s); s != "" {
|
||||||
|
allowedScopes[s] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(allowedScopes) > 0 {
|
||||||
|
flagPkg.AllowedScopes = allowedScopes
|
||||||
|
}
|
||||||
|
if getenv("GITEA_DEBUG") == "true" {
|
||||||
flagPkg.Debug = true
|
flagPkg.Debug = true
|
||||||
}
|
}
|
||||||
|
if getenv("GITEA_INSECURE") == "true" {
|
||||||
// Set insecure mode based on environment variable
|
|
||||||
if os.Getenv("GITEA_INSECURE") == "true" {
|
|
||||||
flagPkg.Insecure = true
|
flagPkg.Insecure = true
|
||||||
}
|
}
|
||||||
|
if !maxInlineAttachmentBytesFlagSet {
|
||||||
|
if val := getenv("GITEA_MAX_INLINE_ATTACHMENT_BYTES"); val != "" {
|
||||||
|
parsed, err := strconv.Atoi(val)
|
||||||
|
if err != nil || parsed < 0 {
|
||||||
|
fmt.Fprintf(stderr, "invalid GITEA_MAX_INLINE_ATTACHMENT_BYTES: %q\n", val)
|
||||||
|
osExit(1)
|
||||||
|
}
|
||||||
|
flagPkg.MaxInlineAttachmentBytes = parsed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeScope trims whitespace, lowercases, and converts internal spaces
|
||||||
|
// and hyphens to underscores, so "Pull Request", "pull-request", and
|
||||||
|
// "PULL_REQUEST" all normalize to "pull_request".
|
||||||
|
func normalizeScope(s string) string {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
s = strings.ToLower(s)
|
||||||
|
s = strings.ReplaceAll(s, " ", "_")
|
||||||
|
s = strings.ReplaceAll(s, "-", "_")
|
||||||
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
func Execute() {
|
func Execute() {
|
||||||
|
initFlagSet(flag.CommandLine, os.Args[1:], os.Getenv, os.ReadFile, os.Stderr)
|
||||||
if version {
|
if version {
|
||||||
fmt.Fprintln(os.Stdout, flagPkg.Version)
|
fmt.Fprintln(os.Stdout, flagPkg.Version)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer log.Default().Sync() //nolint:errcheck // best-effort flush
|
|
||||||
if err := operation.Run(); err != nil {
|
if err := operation.Run(); err != nil {
|
||||||
if err == context.Canceled {
|
if err == context.Canceled {
|
||||||
log.Info("Server shutdown due to context cancellation")
|
log.Info("Server shutdown due to context cancellation")
|
||||||
|
_ = log.Default().Sync() // best-effort flush
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Fatalf("Run Gitea MCP Server Error: %v", err) //nolint:gocritic // intentional exit after defer
|
_ = log.Default().Sync() // best-effort flush
|
||||||
|
log.Fatalf("Run Gitea MCP Server Error: %v", err)
|
||||||
}
|
}
|
||||||
|
_ = log.Default().Sync() // best-effort flush
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"flag"
|
||||||
|
"maps"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
flagPkg "gitea.com/gitea/gitea-mcp/pkg/flag"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInitFlagSetScopes(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
env map[string]string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "no scope flag or env leaves AllowedScopes unset",
|
||||||
|
args: []string{},
|
||||||
|
want: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "-S sets a single scope",
|
||||||
|
args: []string{"-S", "repository"},
|
||||||
|
want: []string{"repository"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "-scope sets a comma-separated list",
|
||||||
|
args: []string{"-scope", "repository,file"},
|
||||||
|
want: []string{"file", "repository"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "GITEA_SCOPES env sets the default",
|
||||||
|
args: []string{},
|
||||||
|
env: map[string]string{"GITEA_SCOPES": "issue,pull_request"},
|
||||||
|
want: []string{"issue", "pull_request"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "-S flag takes precedence over GITEA_SCOPES env",
|
||||||
|
args: []string{"-S", "file"},
|
||||||
|
env: map[string]string{"GITEA_SCOPES": "issue"},
|
||||||
|
want: []string{"file"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "normalizes case, whitespace, and hyphens/spaces to underscores",
|
||||||
|
args: []string{"-S", " Pull Request , pull-request , PULL_REQUEST "},
|
||||||
|
want: []string{"pull_request"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
origScopes := flagPkg.AllowedScopes
|
||||||
|
t.Cleanup(func() {
|
||||||
|
flagPkg.AllowedScopes = origScopes
|
||||||
|
})
|
||||||
|
flagPkg.AllowedScopes = nil
|
||||||
|
|
||||||
|
getenv := func(key string) string { return tt.env[key] }
|
||||||
|
readFile := func(string) ([]byte, error) { return nil, nil }
|
||||||
|
fs := flag.NewFlagSet("test", flag.ContinueOnError)
|
||||||
|
var stderr bytes.Buffer
|
||||||
|
|
||||||
|
initFlagSet(fs, tt.args, getenv, readFile, &stderr)
|
||||||
|
|
||||||
|
got := slices.Sorted(maps.Keys(flagPkg.AllowedScopes))
|
||||||
|
want := slices.Clone(tt.want)
|
||||||
|
slices.Sort(want)
|
||||||
|
if !slices.Equal(got, want) {
|
||||||
|
t.Errorf("AllowedScopes = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,4 +5,4 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Tool is the registry for all Actions-related MCP tools.
|
// Tool is the registry for all Actions-related MCP tools.
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("actions")
|
||||||
|
|||||||
@@ -29,12 +29,12 @@ var (
|
|||||||
ActionsRunReadToolName,
|
ActionsRunReadToolName,
|
||||||
mcp.WithDescription("Read Actions workflows, runs, jobs, logs, and artifacts."),
|
mcp.WithDescription("Read Actions workflows, runs, jobs, logs, and artifacts."),
|
||||||
mcp.WithToolAnnotation(annotation.ReadOnly("Read Actions workflow, run, job, and artifact data")),
|
mcp.WithToolAnnotation(annotation.ReadOnly("Read Actions workflow, run, job, and artifact data")),
|
||||||
mcp.WithString("method", mcp.Required(), mcp.Enum("list_workflows", "get_workflow", "list_runs", "get_run", "list_jobs", "list_run_jobs", "get_job_log_preview", "download_job_log", "list_artifacts", "list_run_artifacts", "get_artifact", "download_artifact")),
|
mcp.WithString("method", mcp.Required(), mcp.Enum("list_workflows", "get_workflow", "list_runs", "get_run", "list_jobs", "list_run_jobs", "get_job", "get_job_log_preview", "download_job_log", "list_artifacts", "list_run_artifacts", "get_artifact", "download_artifact")),
|
||||||
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
|
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
|
||||||
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
|
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
|
||||||
mcp.WithString("workflow_id", mcp.Description("ID or filename (for 'get_workflow')")),
|
mcp.WithString("workflow_id", mcp.Description("ID or filename (for 'get_workflow')")),
|
||||||
mcp.WithNumber("run_id", mcp.Description("for 'get_run'/'list_run_jobs'/'list_run_artifacts'")),
|
mcp.WithNumber("run_id", mcp.Description("for 'get_run'/'list_run_jobs'/'list_run_artifacts'")),
|
||||||
mcp.WithNumber("job_id", mcp.Description("for log methods")),
|
mcp.WithNumber("job_id", mcp.Description("for 'get_job'/log methods")),
|
||||||
mcp.WithNumber("artifact_id", mcp.Description("for 'get_artifact'/'download_artifact'")),
|
mcp.WithNumber("artifact_id", mcp.Description("for 'get_artifact'/'download_artifact'")),
|
||||||
mcp.WithString("artifact_name", mcp.Description("name filter for 'list_artifacts'/'list_run_artifacts'")),
|
mcp.WithString("artifact_name", mcp.Description("name filter for 'list_artifacts'/'list_run_artifacts'")),
|
||||||
mcp.WithString("status", mcp.Description("filter for 'list_runs'/'list_jobs'")),
|
mcp.WithString("status", mcp.Description("filter for 'list_runs'/'list_jobs'")),
|
||||||
@@ -82,6 +82,8 @@ func runReadFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResul
|
|||||||
return listRepoActionJobsFn(ctx, req)
|
return listRepoActionJobsFn(ctx, req)
|
||||||
case "list_run_jobs":
|
case "list_run_jobs":
|
||||||
return listRepoActionRunJobsFn(ctx, req)
|
return listRepoActionRunJobsFn(ctx, req)
|
||||||
|
case "get_job":
|
||||||
|
return getRepoActionJobFn(ctx, req)
|
||||||
case "get_job_log_preview":
|
case "get_job_log_preview":
|
||||||
return getRepoActionJobLogPreviewFn(ctx, req)
|
return getRepoActionJobLogPreviewFn(ctx, req)
|
||||||
case "download_job_log":
|
case "download_job_log":
|
||||||
@@ -416,6 +418,37 @@ func listRepoActionRunJobsFn(ctx context.Context, req mcp.CallToolRequest) (*mcp
|
|||||||
return to.TextResult(slimActionJobs(result))
|
return to.TextResult(slimActionJobs(result))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getRepoActionJobFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||||
|
owner, err := params.GetString(req.GetArguments(), "owner")
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
repo, err := params.GetString(req.GetArguments(), "repo")
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
jobID, err := params.GetIndex(req.GetArguments(), "job_id")
|
||||||
|
if err != nil || jobID <= 0 {
|
||||||
|
return to.ErrorResult(errors.New("job_id is required"))
|
||||||
|
}
|
||||||
|
|
||||||
|
var result any
|
||||||
|
err = doJSONWithFallback(ctx, "GET",
|
||||||
|
[]string{
|
||||||
|
fmt.Sprintf("repos/%s/%s/actions/jobs/%d", url.PathEscape(owner), url.PathEscape(repo), jobID),
|
||||||
|
},
|
||||||
|
nil, nil, &result,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
var httpErr *gitea.HTTPError
|
||||||
|
if errors.As(err, &httpErr) && (httpErr.StatusCode == http.StatusNotFound || httpErr.StatusCode == http.StatusMethodNotAllowed) {
|
||||||
|
return to.ErrorResult(fmt.Errorf("get action job not supported on this Gitea version (endpoint returned %d, requires Gitea 1.26+). Check https://docs.gitea.com/api/1.26/ for available Actions endpoints", httpErr.StatusCode))
|
||||||
|
}
|
||||||
|
return to.ErrorResult(fmt.Errorf("get action job err: %v", err))
|
||||||
|
}
|
||||||
|
return to.TextResult(slimActionJob(result))
|
||||||
|
}
|
||||||
|
|
||||||
func logPaths(owner, repo string, jobID int64) []string {
|
func logPaths(owner, repo string, jobID int64) []string {
|
||||||
return []string{
|
return []string{
|
||||||
fmt.Sprintf("repos/%s/%s/actions/jobs/%d/logs", url.PathEscape(owner), url.PathEscape(repo), jobID),
|
fmt.Sprintf("repos/%s/%s/actions/jobs/%d/logs", url.PathEscape(owner), url.PathEscape(repo), jobID),
|
||||||
|
|||||||
@@ -76,6 +76,13 @@ func slimActionRuns(raw any) any {
|
|||||||
return slimPaginated(raw, slimRun)
|
return slimPaginated(raw, slimRun)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func slimActionJob(raw any) any {
|
||||||
|
if m, ok := raw.(map[string]any); ok {
|
||||||
|
return slimJob(m)
|
||||||
|
}
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
func slimActionJobs(raw any) any {
|
func slimActionJobs(raw any) any {
|
||||||
return slimPaginated(raw, slimJob)
|
return slimPaginated(raw, slimJob)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package actions
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestSlimActionJobKeepsExpectedKeys(t *testing.T) {
|
||||||
|
raw := map[string]any{
|
||||||
|
"id": float64(42),
|
||||||
|
"run_id": float64(7),
|
||||||
|
"name": "build",
|
||||||
|
"workflow_name": "CI",
|
||||||
|
"status": "completed",
|
||||||
|
"conclusion": "success",
|
||||||
|
"html_url": "https://gitea.example/x",
|
||||||
|
"started_at": "2026-01-01T00:00:00Z",
|
||||||
|
"completed_at": "2026-01-01T00:01:00Z",
|
||||||
|
"steps": []any{
|
||||||
|
map[string]any{"name": "checkout", "number": float64(1), "status": "completed", "conclusion": "success", "extra": "drop me"},
|
||||||
|
},
|
||||||
|
// fields that must be dropped
|
||||||
|
"head_sha": "deadbeef",
|
||||||
|
"runner_name": "runner-1",
|
||||||
|
}
|
||||||
|
|
||||||
|
out, ok := slimActionJob(raw).(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("slimActionJob did not return a map, got %T", slimActionJob(raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, k := range []string{"id", "run_id", "name", "workflow_name", "status", "conclusion", "html_url", "started_at", "completed_at", "steps"} {
|
||||||
|
if _, present := out[k]; !present {
|
||||||
|
t.Errorf("expected key %q to be kept", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, k := range []string{"head_sha", "runner_name"} {
|
||||||
|
if _, present := out[k]; present {
|
||||||
|
t.Errorf("expected key %q to be dropped", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
steps, ok := out["steps"].([]any)
|
||||||
|
if !ok || len(steps) != 1 {
|
||||||
|
t.Fatalf("expected 1 slimmed step, got %v", out["steps"])
|
||||||
|
}
|
||||||
|
step := steps[0].(map[string]any)
|
||||||
|
if _, present := step["extra"]; present {
|
||||||
|
t.Errorf("expected step field 'extra' to be dropped")
|
||||||
|
}
|
||||||
|
if step["name"] != "checkout" {
|
||||||
|
t.Errorf("expected step name 'checkout', got %v", step["name"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSlimActionJobPassesThroughNonMap(t *testing.T) {
|
||||||
|
if got := slimActionJob("not-a-map"); got != "not-a-map" {
|
||||||
|
t.Errorf("expected passthrough, got %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
package issue
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/annotation"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/flag"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/params"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/to"
|
||||||
|
|
||||||
|
gitea_sdk "gitea.dev/sdk"
|
||||||
|
"github.com/mark3labs/mcp-go/mcp"
|
||||||
|
"github.com/mark3labs/mcp-go/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
const AttachmentReadToolName = "attachment_read"
|
||||||
|
|
||||||
|
var AttachmentReadTool = mcp.NewTool(
|
||||||
|
AttachmentReadToolName,
|
||||||
|
mcp.WithDescription("Read issue/comment attachments: list metadata, get metadata, or download content."),
|
||||||
|
mcp.WithToolAnnotation(annotation.ReadOnly("Read issue or comment attachments")),
|
||||||
|
mcp.WithString("method", mcp.Required(), mcp.Enum("list", "get", "download")),
|
||||||
|
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
|
||||||
|
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
|
||||||
|
mcp.WithNumber("issue_number", mcp.Description("required for issue attachment list/get or issue-scoped metadata lookup")),
|
||||||
|
mcp.WithNumber("comment_id", mcp.Description("required for comment attachment list/get or comment-scoped metadata lookup")),
|
||||||
|
mcp.WithNumber("attachment_id", mcp.Description("required for get and for download when attachment_uuid is not provided")),
|
||||||
|
mcp.WithString("attachment_uuid", mcp.Description("attachment UUID for direct download path lookup")),
|
||||||
|
mcp.WithString("output_path", mcp.Description("write the attachment to this exact path")),
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
Tool.RegisterRead(server.ServerTool{Tool: AttachmentReadTool, Handler: attachmentReadFn})
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentReadFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||||
|
method, err := params.GetString(req.GetArguments(), "method")
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
switch method {
|
||||||
|
case "list":
|
||||||
|
return listAttachmentsFn(ctx, req)
|
||||||
|
case "get":
|
||||||
|
return getAttachmentFn(ctx, req)
|
||||||
|
case "download":
|
||||||
|
return downloadAttachmentFn(ctx, req)
|
||||||
|
default:
|
||||||
|
return to.ErrorResult(fmt.Errorf("unknown method: %s", method))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listAttachmentsFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||||
|
owner, repo, issueNumber, commentID, err := attachmentScopeArgs(req)
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
client, err := gitea.ClientFromContext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
|
||||||
|
}
|
||||||
|
var attachments []*gitea_sdk.Attachment
|
||||||
|
if issueNumber > 0 {
|
||||||
|
attachments, _, err = client.Issues.ListIssueAttachments(ctx, owner, repo, issueNumber)
|
||||||
|
} else {
|
||||||
|
attachments, _, err = client.Issues.ListIssueCommentAttachments(ctx, owner, repo, commentID)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("list attachments err: %v", err))
|
||||||
|
}
|
||||||
|
return to.TextResult(slimAttachments(attachments))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getAttachmentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||||
|
att, err := lookupAttachment(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
return to.TextResult(slimAttachment(att))
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadAttachmentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||||
|
owner, err := params.GetString(req.GetArguments(), "owner")
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
repo, err := params.GetString(req.GetArguments(), "repo")
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
explicitOutputPath := params.GetOptionalString(req.GetArguments(), "output_path", "")
|
||||||
|
attachmentUUID := strings.TrimSpace(params.GetOptionalString(req.GetArguments(), "attachment_uuid", ""))
|
||||||
|
|
||||||
|
var att *gitea_sdk.Attachment
|
||||||
|
if attachmentUUID == "" {
|
||||||
|
att, err = lookupAttachment(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(err)
|
||||||
|
}
|
||||||
|
attachmentUUID = strings.TrimSpace(att.UUID)
|
||||||
|
}
|
||||||
|
if attachmentUUID == "" {
|
||||||
|
return to.ErrorResult(errors.New("attachment_uuid or attachment metadata with uuid is required"))
|
||||||
|
}
|
||||||
|
|
||||||
|
name := attachmentUUID
|
||||||
|
if att != nil && strings.TrimSpace(att.Name) != "" {
|
||||||
|
name = strings.TrimSpace(att.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := gitea.OpenAttachment(ctx, "/attachments/"+attachmentUUID, "*/*")
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("download attachment err: %v", err))
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
mimeType := normalizeAttachmentContentType(resp.ContentType, name)
|
||||||
|
if explicitOutputPath == "" && shouldInlineAttachment(att, mimeType) {
|
||||||
|
limited, readErr := io.ReadAll(io.LimitReader(resp.Body, int64(flag.MaxInlineAttachmentBytes)+1))
|
||||||
|
if readErr != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("read attachment err: %v", readErr))
|
||||||
|
}
|
||||||
|
if len(limited) <= flag.MaxInlineAttachmentBytes {
|
||||||
|
text := fmt.Sprintf("attachment %s (%s, %d bytes, %s)", name, attachmentUUID, len(limited), mimeType)
|
||||||
|
return mcp.NewToolResultImage(text, base64.StdEncoding.EncodeToString(limited), mimeType), nil
|
||||||
|
}
|
||||||
|
outputPath := defaultAttachmentPath(owner, repo, name, attachmentUUID)
|
||||||
|
if err := os.MkdirAll(filepath.Dir(outputPath), 0o700); err != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("create output dir err: %v", err))
|
||||||
|
}
|
||||||
|
reader := io.MultiReader(bytes.NewReader(limited), resp.Body)
|
||||||
|
written, err := gitea.WriteAttachment(reader, outputPath)
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("write attachment file err: %v", err))
|
||||||
|
}
|
||||||
|
return attachmentFileResult(att, outputPath, written, name, attachmentUUID, mimeType)
|
||||||
|
}
|
||||||
|
|
||||||
|
outputPath := explicitOutputPath
|
||||||
|
if outputPath == "" {
|
||||||
|
outputPath = defaultAttachmentPath(owner, repo, name, attachmentUUID)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(outputPath), 0o700); err != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("create output dir err: %v", err))
|
||||||
|
}
|
||||||
|
written, err := gitea.WriteAttachment(resp.Body, outputPath)
|
||||||
|
if err != nil {
|
||||||
|
return to.ErrorResult(fmt.Errorf("write attachment file err: %v", err))
|
||||||
|
}
|
||||||
|
return attachmentFileResult(att, outputPath, written, name, attachmentUUID, mimeType)
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldInlineAttachment(att *gitea_sdk.Attachment, mimeType string) bool {
|
||||||
|
if !strings.HasPrefix(mimeType, "image/") || flag.MaxInlineAttachmentBytes <= 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if att == nil || att.Size <= 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return att.Size <= int64(flag.MaxInlineAttachmentBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentFileResult(att *gitea_sdk.Attachment, outputPath string, written int64, name, attachmentUUID, mimeType string) (*mcp.CallToolResult, error) {
|
||||||
|
res := map[string]any{
|
||||||
|
"path": outputPath,
|
||||||
|
"bytes": written,
|
||||||
|
"name": name,
|
||||||
|
"uuid": attachmentUUID,
|
||||||
|
"mime_type": mimeType,
|
||||||
|
"content_type": mimeType,
|
||||||
|
}
|
||||||
|
if att != nil {
|
||||||
|
res["attachment_id"] = att.ID
|
||||||
|
}
|
||||||
|
return to.TextResult(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentScopeArgs(req mcp.CallToolRequest) (owner, repo string, issueNumber, commentID int64, err error) {
|
||||||
|
owner, err = params.GetString(req.GetArguments(), "owner")
|
||||||
|
if err != nil {
|
||||||
|
return "", "", 0, 0, err
|
||||||
|
}
|
||||||
|
repo, err = params.GetString(req.GetArguments(), "repo")
|
||||||
|
if err != nil {
|
||||||
|
return "", "", 0, 0, err
|
||||||
|
}
|
||||||
|
issueNumber = params.GetOptionalInt(req.GetArguments(), "issue_number", 0)
|
||||||
|
commentID = params.GetOptionalInt(req.GetArguments(), "comment_id", 0)
|
||||||
|
if (issueNumber > 0) == (commentID > 0) {
|
||||||
|
return "", "", 0, 0, errors.New("exactly one of issue_number or comment_id is required")
|
||||||
|
}
|
||||||
|
return owner, repo, issueNumber, commentID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupAttachment(ctx context.Context, req mcp.CallToolRequest) (*gitea_sdk.Attachment, error) {
|
||||||
|
owner, repo, issueNumber, commentID, err := attachmentScopeArgs(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
attachmentID := params.GetOptionalInt(req.GetArguments(), "attachment_id", 0)
|
||||||
|
if attachmentID <= 0 {
|
||||||
|
return nil, errors.New("attachment_id is required")
|
||||||
|
}
|
||||||
|
client, err := gitea.ClientFromContext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("get gitea client err: %v", err)
|
||||||
|
}
|
||||||
|
if issueNumber > 0 {
|
||||||
|
att, _, err := client.Issues.GetIssueAttachment(ctx, owner, repo, issueNumber, attachmentID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("get issue attachment err: %v", err)
|
||||||
|
}
|
||||||
|
return att, nil
|
||||||
|
}
|
||||||
|
att, _, err := client.Issues.GetIssueCommentAttachment(ctx, owner, repo, commentID, attachmentID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("get issue comment attachment err: %v", err)
|
||||||
|
}
|
||||||
|
return att, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func slimAttachments(atts []*gitea_sdk.Attachment) []map[string]any {
|
||||||
|
out := make([]map[string]any, 0, len(atts))
|
||||||
|
for _, att := range atts {
|
||||||
|
out = append(out, slimAttachment(att))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func slimAttachment(att *gitea_sdk.Attachment) map[string]any {
|
||||||
|
if att == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m := map[string]any{
|
||||||
|
"id": att.ID,
|
||||||
|
"name": att.Name,
|
||||||
|
"uuid": att.UUID,
|
||||||
|
"size": att.Size,
|
||||||
|
"download_count": att.DownloadCount,
|
||||||
|
"created_at": att.Created,
|
||||||
|
"mime_type": inferAttachmentMimeType(att.Name),
|
||||||
|
}
|
||||||
|
if att.DownloadURL != "" {
|
||||||
|
m["browser_download_url"] = att.DownloadURL
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
func inferAttachmentMimeType(name string) string {
|
||||||
|
if ext := strings.ToLower(filepath.Ext(strings.TrimSpace(name))); ext != "" {
|
||||||
|
if mimeType := mime.TypeByExtension(ext); mimeType != "" {
|
||||||
|
return strings.Split(mimeType, ";")[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "application/octet-stream"
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeAttachmentContentType(contentType, name string) string {
|
||||||
|
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||||
|
if err == nil && mediaType != "" && mediaType != "application/octet-stream" {
|
||||||
|
return mediaType
|
||||||
|
}
|
||||||
|
return inferAttachmentMimeType(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultAttachmentPath(owner, repo, name, uuid string) string {
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
if home == "" {
|
||||||
|
home = os.TempDir()
|
||||||
|
}
|
||||||
|
filename := attachmentFilename(name, uuid)
|
||||||
|
ext := filepath.Ext(filename)
|
||||||
|
base := strings.TrimSuffix(filename, ext)
|
||||||
|
if uuid != "" {
|
||||||
|
filename = uuid
|
||||||
|
if base != "" && base != "attachment" {
|
||||||
|
filename = base + "-" + uuid
|
||||||
|
}
|
||||||
|
filename += ext
|
||||||
|
}
|
||||||
|
return filepath.Join(home, ".gitea-mcp", "attachments", safePathPart(owner), safePathPart(repo), filename)
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentFilename(name, uuid string) string {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name != "" && !strings.ContainsAny(name, `/\\`) && name != "." && name != ".." {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
if uuid != "" {
|
||||||
|
return uuid + ".bin"
|
||||||
|
}
|
||||||
|
return "attachment.bin"
|
||||||
|
}
|
||||||
|
|
||||||
|
func safePathPart(name string) string {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name != "" && !strings.ContainsAny(name, `/\\`) && name != "." && name != ".." {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package issue
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/flag"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
||||||
|
|
||||||
|
"github.com/mark3labs/mcp-go/mcp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAttachmentFilename(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
file string
|
||||||
|
uuid string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"uses attachment name", "screenshot.png", "abc", "screenshot.png"},
|
||||||
|
{"falls back for traversal", "../etc/passwd", "abc", "abc.bin"},
|
||||||
|
{"falls back for empty name", "", "abc", "abc.bin"},
|
||||||
|
{"uses generic fallback", "", "", "attachment.bin"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := attachmentFilename(tt.file, tt.uuid); got != tt.want {
|
||||||
|
t.Fatalf("attachmentFilename() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInferAttachmentMimeType(t *testing.T) {
|
||||||
|
if got := inferAttachmentMimeType("shot.png"); got != "image/png" {
|
||||||
|
t.Fatalf("inferAttachmentMimeType() = %q, want image/png", got)
|
||||||
|
}
|
||||||
|
if got := inferAttachmentMimeType("archive.unknownext"); got != "application/octet-stream" {
|
||||||
|
t.Fatalf("inferAttachmentMimeType() = %q, want application/octet-stream", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultAttachmentPath(t *testing.T) {
|
||||||
|
got := defaultAttachmentPath("octo", "demo", "shot.png", "uuid-1")
|
||||||
|
want := filepath.Join(".gitea-mcp", "attachments", "octo", "demo", "shot-uuid-1.png")
|
||||||
|
if !strings.HasSuffix(got, want) {
|
||||||
|
t.Fatalf("defaultAttachmentPath() = %q, want suffix %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttachmentReadListIssueAttachments(t *testing.T) {
|
||||||
|
const owner = "octo"
|
||||||
|
const repo = "demo"
|
||||||
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/v1/version":
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"version":"1.12.0"}`))
|
||||||
|
case fmt.Sprintf("/api/v1/repos/%s/%s", owner, repo):
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"private":false}`))
|
||||||
|
case fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/assets", owner, repo):
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`[{"id":1,"name":"shot.png","uuid":"uuid-1","size":10,"download_count":2}]`))
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
defer server.Close()
|
||||||
|
origHost, origToken, origVersion := flag.Host, flag.Token, flag.Version
|
||||||
|
flag.Host, flag.Token, flag.Version = server.URL, "", "test"
|
||||||
|
defer func() { flag.Host, flag.Token, flag.Version = origHost, origToken, origVersion }()
|
||||||
|
|
||||||
|
res, err := attachmentReadFn(context.Background(), mcp.CallToolRequest{Params: mcp.CallToolParams{Arguments: map[string]any{
|
||||||
|
"method": "list", "owner": owner, "repo": repo, "issue_number": float64(42),
|
||||||
|
}}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("attachmentReadFn() error = %v", err)
|
||||||
|
}
|
||||||
|
body := res.Content[0].(mcp.TextContent).Text
|
||||||
|
if !strings.Contains(body, `"mime_type":"image/png"`) || !strings.Contains(body, `"uuid":"uuid-1"`) {
|
||||||
|
t.Fatalf("unexpected body: %s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDownloadAttachmentRejectsRedirectLoopAtHopLimit(t *testing.T) {
|
||||||
|
var serverURL string
|
||||||
|
redirects := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/attachments/uuid-1" {
|
||||||
|
t.Fatalf("path = %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
redirects++
|
||||||
|
http.Redirect(w, r, serverURL+"/attachments/uuid-1", http.StatusFound)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
serverURL = server.URL
|
||||||
|
|
||||||
|
origHost := flag.Host
|
||||||
|
flag.Host = server.URL
|
||||||
|
defer func() { flag.Host = origHost }()
|
||||||
|
|
||||||
|
_, _, _, err := gitea.DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected redirect limit error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "stopped after 10 redirects") {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if redirects != 10 {
|
||||||
|
t.Fatalf("redirects = %d, want 10", redirects)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttachmentReadDownloadSavesLargeAttachmentToDefaultFile(t *testing.T) {
|
||||||
|
const owner = "octo"
|
||||||
|
const repo = "demo"
|
||||||
|
const uuid = "uuid-1"
|
||||||
|
const name = "large.bin"
|
||||||
|
payload := strings.Repeat("a", 32)
|
||||||
|
|
||||||
|
home := t.TempDir()
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
|
||||||
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/v1/version":
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"version":"1.12.0"}`))
|
||||||
|
case fmt.Sprintf("/api/v1/repos/%s/%s", owner, repo):
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"private":false}`))
|
||||||
|
case fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/assets/1", owner, repo):
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "name": name, "uuid": uuid, "size": len(payload)})
|
||||||
|
case "/attachments/" + uuid:
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
_, _ = w.Write([]byte(payload))
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
origHost, origToken, origVersion, origInline := flag.Host, flag.Token, flag.Version, flag.MaxInlineAttachmentBytes
|
||||||
|
flag.Host, flag.Token, flag.Version = server.URL, "", "test"
|
||||||
|
flag.MaxInlineAttachmentBytes = 8
|
||||||
|
defer func() {
|
||||||
|
flag.Host, flag.Token, flag.Version, flag.MaxInlineAttachmentBytes = origHost, origToken, origVersion, origInline
|
||||||
|
}()
|
||||||
|
|
||||||
|
res, err := attachmentReadFn(context.Background(), mcp.CallToolRequest{Params: mcp.CallToolParams{Arguments: map[string]any{
|
||||||
|
"method": "download", "owner": owner, "repo": repo, "issue_number": float64(42), "attachment_id": float64(1),
|
||||||
|
}}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("attachmentReadFn() error = %v", err)
|
||||||
|
}
|
||||||
|
body := res.Content[0].(mcp.TextContent).Text
|
||||||
|
wantPath := filepath.Join(home, ".gitea-mcp", "attachments", owner, repo, "large-uuid-1.bin")
|
||||||
|
if !strings.Contains(body, wantPath) {
|
||||||
|
t.Fatalf("result missing path %q: %s", wantPath, body)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(wantPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadFile(%q): %v", wantPath, err)
|
||||||
|
}
|
||||||
|
if string(data) != payload {
|
||||||
|
t.Fatalf("saved payload mismatch")
|
||||||
|
}
|
||||||
|
if !strings.Contains(body, `"bytes":32`) {
|
||||||
|
t.Fatalf("result missing bytes: %s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,7 +29,7 @@ type commentWithAssets struct {
|
|||||||
Assets []*gitea_sdk.Attachment `json:"assets"`
|
Assets []*gitea_sdk.Attachment `json:"assets"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("issue")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ListRepoIssuesToolName = "list_issues"
|
ListRepoIssuesToolName = "list_issues"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("label")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
LabelReadToolName = "label_read"
|
LabelReadToolName = "label_read"
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("milestone")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
MilestoneReadToolName = "milestone_read"
|
MilestoneReadToolName = "milestone_read"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("notification")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
NotificationReadToolName = "notification_read"
|
NotificationReadToolName = "notification_read"
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ var (
|
|||||||
user.Tool, actions.Tool, repo.Tool, notification.Tool, issue.Tool,
|
user.Tool, actions.Tool, repo.Tool, notification.Tool, issue.Tool,
|
||||||
label.Tool, milestone.Tool, packages.Tool, pull.Tool, search.Tool,
|
label.Tool, milestone.Tool, packages.Tool, pull.Tool, search.Tool,
|
||||||
version.Tool, wiki.Tool, timetracking.Tool,
|
version.Tool, wiki.Tool, timetracking.Tool,
|
||||||
|
repo.FileTool, repo.BranchTool, repo.TagTool, repo.CommitTool, repo.ReleaseTool,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -47,6 +48,7 @@ func RegisterTool(s *server.MCPServer) {
|
|||||||
s.AddTools(t.Tools()...)
|
s.AddTools(t.Tools()...)
|
||||||
}
|
}
|
||||||
tool.WarnUnmatchedAllowedTools(domainTools...)
|
tool.WarnUnmatchedAllowedTools(domainTools...)
|
||||||
|
tool.WarnUnmatchedAllowedScopes(domainTools...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseAuthToken extracts the token from an Authorization header.
|
// parseAuthToken extracts the token from an Authorization header.
|
||||||
|
|||||||
@@ -32,6 +32,26 @@ func TestAllToolsHaveDescriptions(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDomainToolsScopesAreUniqueAndNonEmpty ensures every entry registered in
|
||||||
|
// domainTools has a canonical, non-empty scope name and that no two domains
|
||||||
|
// share the same scope (each domain.Tools() call is filtered by exactly one
|
||||||
|
// scope name via flag.AllowedScopes).
|
||||||
|
func TestDomainToolsScopesAreUniqueAndNonEmpty(t *testing.T) {
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
for _, d := range domainTools {
|
||||||
|
scope := d.Scope()
|
||||||
|
if scope == "" {
|
||||||
|
t.Errorf("domainTools contains a domain with an empty scope")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[scope]; ok {
|
||||||
|
t.Errorf("domainTools contains a duplicate scope %q", scope)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[scope] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseAuthToken(t *testing.T) {
|
func TestParseAuthToken(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("packages")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
PackageReadToolName = "package_read"
|
PackageReadToolName = "package_read"
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("pull_request")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ListRepoPullRequestsToolName = "list_pull_requests"
|
ListRepoPullRequestsToolName = "list_pull_requests"
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package operation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"maps"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// toolTableRow matches a row of the "Available Tools" table in the README
|
||||||
|
// files, capturing the tool name, the scope cell and the access cell, e.g.
|
||||||
|
// "| get_me | user | Read | Get the current authenticated user |".
|
||||||
|
var toolTableRow = regexp.MustCompile(`^\|\s*([a-z_]+)\s*\|\s*([a-z_]+)\s*\|\s*(\S+)\s*\|`)
|
||||||
|
|
||||||
|
// readmeAccessLabels maps each README to the access-column labels it uses.
|
||||||
|
var readmeAccessLabels = map[string]map[string]string{
|
||||||
|
"../README.md": {"Read": "read", "Write": "write"},
|
||||||
|
"../README.zh-cn.md": {"读取": "read", "写入": "write"},
|
||||||
|
"../README.zh-tw.md": {"讀取": "read", "寫入": "write"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// toolInfo is what TestReadmeToolTables tracks per tool, both as registered
|
||||||
|
// in code and as documented in a README, so the two can be compared.
|
||||||
|
type toolInfo struct {
|
||||||
|
scope string
|
||||||
|
access string
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReadmeToolTables ensures the tool tables in the README files stay in sync
|
||||||
|
// with the registered tools, in both directions and for every translation.
|
||||||
|
// The tables listed tools that no longer existed for several releases before
|
||||||
|
// anyone noticed.
|
||||||
|
// The scope names in the README are the canonical, lowercase snake_case names
|
||||||
|
// returned by (*tool.Tool).Scope(), so no translation is needed to compare them.
|
||||||
|
func TestReadmeToolTables(t *testing.T) {
|
||||||
|
registered := map[string]toolInfo{}
|
||||||
|
for _, d := range domainTools {
|
||||||
|
scope := d.Scope()
|
||||||
|
for _, st := range d.ReadTools() {
|
||||||
|
registered[st.Tool.Name] = toolInfo{scope: scope, access: "read"}
|
||||||
|
}
|
||||||
|
for _, st := range d.WriteTools() {
|
||||||
|
registered[st.Tool.Name] = toolInfo{scope: scope, access: "write"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for path, labels := range readmeAccessLabels {
|
||||||
|
t.Run(filepath.Base(path), func(t *testing.T) {
|
||||||
|
content, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
documented := map[string]toolInfo{}
|
||||||
|
for line := range strings.SplitSeq(string(content), "\n") {
|
||||||
|
if match := toolTableRow.FindStringSubmatch(line); match != nil {
|
||||||
|
documented[match[1]] = toolInfo{scope: match[2], access: labels[match[3]]}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range slices.Sorted(maps.Keys(registered)) {
|
||||||
|
got, ok := documented[name]
|
||||||
|
want := registered[name]
|
||||||
|
switch {
|
||||||
|
case !ok:
|
||||||
|
t.Errorf("tool %q is registered but missing from the tool table", name)
|
||||||
|
case got.access != want.access:
|
||||||
|
t.Errorf("tool %q is documented with %q access, want %q", name, got.access, want.access)
|
||||||
|
case got.scope != want.scope:
|
||||||
|
t.Errorf("tool %q is documented with scope %q, want %q", name, got.scope, want.scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range slices.Sorted(maps.Keys(documented)) {
|
||||||
|
if _, ok := registered[name]; !ok {
|
||||||
|
t.Errorf("tool %q is in the tool table but is not registered", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,12 +8,16 @@ import (
|
|||||||
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/params"
|
"gitea.com/gitea/gitea-mcp/pkg/params"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/to"
|
"gitea.com/gitea/gitea-mcp/pkg/to"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
||||||
|
|
||||||
gitea_sdk "gitea.dev/sdk"
|
gitea_sdk "gitea.dev/sdk"
|
||||||
"github.com/mark3labs/mcp-go/mcp"
|
"github.com/mark3labs/mcp-go/mcp"
|
||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// BranchTool holds the branch-related tools (scope "branch").
|
||||||
|
var BranchTool = tool.New("branch")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CreateBranchToolName = "create_branch"
|
CreateBranchToolName = "create_branch"
|
||||||
DeleteBranchToolName = "delete_branch"
|
DeleteBranchToolName = "delete_branch"
|
||||||
@@ -52,15 +56,15 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
BranchTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: CreateBranchTool,
|
Tool: CreateBranchTool,
|
||||||
Handler: CreateBranchFn,
|
Handler: CreateBranchFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
BranchTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: DeleteBranchTool,
|
Tool: DeleteBranchTool,
|
||||||
Handler: DeleteBranchFn,
|
Handler: DeleteBranchFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
BranchTool.RegisterRead(server.ServerTool{
|
||||||
Tool: ListBranchesTool,
|
Tool: ListBranchesTool,
|
||||||
Handler: ListBranchesFn,
|
Handler: ListBranchesFn,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -8,12 +8,16 @@ import (
|
|||||||
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/params"
|
"gitea.com/gitea/gitea-mcp/pkg/params"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/to"
|
"gitea.com/gitea/gitea-mcp/pkg/to"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
||||||
|
|
||||||
gitea_sdk "gitea.dev/sdk"
|
gitea_sdk "gitea.dev/sdk"
|
||||||
"github.com/mark3labs/mcp-go/mcp"
|
"github.com/mark3labs/mcp-go/mcp"
|
||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// CommitTool holds the commit-related tools (scope "commit").
|
||||||
|
var CommitTool = tool.New("commit")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ListRepoCommitsToolName = "list_commits"
|
ListRepoCommitsToolName = "list_commits"
|
||||||
GetCommitToolName = "get_commit"
|
GetCommitToolName = "get_commit"
|
||||||
@@ -43,11 +47,11 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
Tool.RegisterRead(server.ServerTool{
|
CommitTool.RegisterRead(server.ServerTool{
|
||||||
Tool: ListRepoCommitsTool,
|
Tool: ListRepoCommitsTool,
|
||||||
Handler: ListRepoCommitsFn,
|
Handler: ListRepoCommitsFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
CommitTool.RegisterRead(server.ServerTool{
|
||||||
Tool: GetCommitTool,
|
Tool: GetCommitTool,
|
||||||
Handler: GetCommitFn,
|
Handler: GetCommitFn,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -12,12 +12,16 @@ import (
|
|||||||
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/params"
|
"gitea.com/gitea/gitea-mcp/pkg/params"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/to"
|
"gitea.com/gitea/gitea-mcp/pkg/to"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
||||||
|
|
||||||
gitea_sdk "gitea.dev/sdk"
|
gitea_sdk "gitea.dev/sdk"
|
||||||
"github.com/mark3labs/mcp-go/mcp"
|
"github.com/mark3labs/mcp-go/mcp"
|
||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// FileTool holds the file-related tools (scope "file").
|
||||||
|
var FileTool = tool.New("file")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
GetFileToolName = "get_file_contents"
|
GetFileToolName = "get_file_contents"
|
||||||
GetDirToolName = "get_dir_contents"
|
GetDirToolName = "get_dir_contents"
|
||||||
@@ -75,19 +79,19 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
Tool.RegisterRead(server.ServerTool{
|
FileTool.RegisterRead(server.ServerTool{
|
||||||
Tool: GetFileContentTool,
|
Tool: GetFileContentTool,
|
||||||
Handler: GetFileContentFn,
|
Handler: GetFileContentFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
FileTool.RegisterRead(server.ServerTool{
|
||||||
Tool: GetDirContentTool,
|
Tool: GetDirContentTool,
|
||||||
Handler: GetDirContentFn,
|
Handler: GetDirContentFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
FileTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: CreateOrUpdateFileTool,
|
Tool: CreateOrUpdateFileTool,
|
||||||
Handler: CreateOrUpdateFileFn,
|
Handler: CreateOrUpdateFileFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
FileTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: DeleteFileTool,
|
Tool: DeleteFileTool,
|
||||||
Handler: DeleteFileFn,
|
Handler: DeleteFileFn,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -8,12 +8,16 @@ import (
|
|||||||
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/params"
|
"gitea.com/gitea/gitea-mcp/pkg/params"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/to"
|
"gitea.com/gitea/gitea-mcp/pkg/to"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
||||||
|
|
||||||
gitea_sdk "gitea.dev/sdk"
|
gitea_sdk "gitea.dev/sdk"
|
||||||
"github.com/mark3labs/mcp-go/mcp"
|
"github.com/mark3labs/mcp-go/mcp"
|
||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ReleaseTool holds the release-related tools (scope "release").
|
||||||
|
var ReleaseTool = tool.New("release")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CreateReleaseToolName = "create_release"
|
CreateReleaseToolName = "create_release"
|
||||||
DeleteReleaseToolName = "delete_release"
|
DeleteReleaseToolName = "delete_release"
|
||||||
@@ -77,23 +81,23 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
ReleaseTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: CreateReleaseTool,
|
Tool: CreateReleaseTool,
|
||||||
Handler: CreateReleaseFn,
|
Handler: CreateReleaseFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
ReleaseTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: DeleteReleaseTool,
|
Tool: DeleteReleaseTool,
|
||||||
Handler: DeleteReleaseFn,
|
Handler: DeleteReleaseFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
ReleaseTool.RegisterRead(server.ServerTool{
|
||||||
Tool: GetReleaseTool,
|
Tool: GetReleaseTool,
|
||||||
Handler: GetReleaseFn,
|
Handler: GetReleaseFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
ReleaseTool.RegisterRead(server.ServerTool{
|
||||||
Tool: GetLatestReleaseTool,
|
Tool: GetLatestReleaseTool,
|
||||||
Handler: GetLatestReleaseFn,
|
Handler: GetLatestReleaseFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
ReleaseTool.RegisterRead(server.ServerTool{
|
||||||
Tool: ListReleasesTool,
|
Tool: ListReleasesTool,
|
||||||
Handler: ListReleasesFn,
|
Handler: ListReleasesFn,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("repository")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CreateRepoToolName = "create_repo"
|
CreateRepoToolName = "create_repo"
|
||||||
|
|||||||
@@ -8,12 +8,16 @@ import (
|
|||||||
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/params"
|
"gitea.com/gitea/gitea-mcp/pkg/params"
|
||||||
"gitea.com/gitea/gitea-mcp/pkg/to"
|
"gitea.com/gitea/gitea-mcp/pkg/to"
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
||||||
|
|
||||||
gitea_sdk "gitea.dev/sdk"
|
gitea_sdk "gitea.dev/sdk"
|
||||||
"github.com/mark3labs/mcp-go/mcp"
|
"github.com/mark3labs/mcp-go/mcp"
|
||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TagTool holds the tag-related tools (scope "tag").
|
||||||
|
var TagTool = tool.New("tag")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CreateTagToolName = "create_tag"
|
CreateTagToolName = "create_tag"
|
||||||
DeleteTagToolName = "delete_tag"
|
DeleteTagToolName = "delete_tag"
|
||||||
@@ -63,19 +67,19 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
TagTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: CreateTagTool,
|
Tool: CreateTagTool,
|
||||||
Handler: CreateTagFn,
|
Handler: CreateTagFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterWrite(server.ServerTool{
|
TagTool.RegisterWrite(server.ServerTool{
|
||||||
Tool: DeleteTagTool,
|
Tool: DeleteTagTool,
|
||||||
Handler: DeleteTagFn,
|
Handler: DeleteTagFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
TagTool.RegisterRead(server.ServerTool{
|
||||||
Tool: GetTagTool,
|
Tool: GetTagTool,
|
||||||
Handler: GetTagFn,
|
Handler: GetTagFn,
|
||||||
})
|
})
|
||||||
Tool.RegisterRead(server.ServerTool{
|
TagTool.RegisterRead(server.ServerTool{
|
||||||
Tool: ListTagsTool,
|
Tool: ListTagsTool,
|
||||||
Handler: ListTagsFn,
|
Handler: ListTagsFn,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("search")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
SearchUsersToolName = "search_users"
|
SearchUsersToolName = "search_users"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("timetracking")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
TimetrackingReadToolName = "timetracking_read"
|
TimetrackingReadToolName = "timetracking_read"
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ const (
|
|||||||
GetUserOrgsToolName = "get_user_orgs"
|
GetUserOrgsToolName = "get_user_orgs"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("user")
|
||||||
|
|
||||||
var (
|
var (
|
||||||
GetMyUserInfoTool = mcp.NewTool(
|
GetMyUserInfoTool = mcp.NewTool(
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("version")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
GetGiteaMCPServerVersion = "get_gitea_mcp_server_version"
|
GetGiteaMCPServerVersion = "get_gitea_mcp_server_version"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/mark3labs/mcp-go/server"
|
"github.com/mark3labs/mcp-go/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Tool = tool.New()
|
var Tool = tool.New("wiki")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
WikiReadToolName = "wiki_read"
|
WikiReadToolName = "wiki_read"
|
||||||
|
|||||||
+7
-4
@@ -7,8 +7,11 @@ var (
|
|||||||
Version string
|
Version string
|
||||||
Mode string
|
Mode string
|
||||||
|
|
||||||
Insecure bool
|
MaxInlineAttachmentBytes int
|
||||||
ReadOnly bool
|
|
||||||
Debug bool
|
Insecure bool
|
||||||
AllowedTools map[string]struct{}
|
ReadOnly bool
|
||||||
|
Debug bool
|
||||||
|
AllowedTools map[string]struct{}
|
||||||
|
AllowedScopes map[string]struct{}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package gitea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.com/gitea/gitea-mcp/pkg/flag"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildAttachmentURLRejectsExternalURL(t *testing.T) {
|
||||||
|
origHost := flag.Host
|
||||||
|
flag.Host = "https://example.com"
|
||||||
|
defer func() { flag.Host = origHost }()
|
||||||
|
|
||||||
|
if _, err := buildAttachmentURL("https://evil.example.com/attachments/1"); err == nil {
|
||||||
|
t.Fatal("expected error for full URL attachment path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildAttachmentURLPreservesHostPathPrefix(t *testing.T) {
|
||||||
|
origHost := flag.Host
|
||||||
|
flag.Host = "https://example.com/gitea"
|
||||||
|
defer func() { flag.Host = origHost }()
|
||||||
|
|
||||||
|
got, err := buildAttachmentURL("/attachments/uuid-1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("buildAttachmentURL() error = %v", err)
|
||||||
|
}
|
||||||
|
if got != "https://example.com/gitea/attachments/uuid-1" {
|
||||||
|
t.Fatalf("buildAttachmentURL() = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDownloadAttachmentUsesTokenAndReturnsContentType(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/attachments/uuid-1" {
|
||||||
|
t.Fatalf("path = %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
if got := r.Header.Get("Authorization"); got != "token secret-token" {
|
||||||
|
t.Fatalf("Authorization = %q", got)
|
||||||
|
}
|
||||||
|
if got := r.Header.Get("Accept"); got != "*/*" {
|
||||||
|
t.Fatalf("Accept = %q", got)
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "image/png")
|
||||||
|
_, _ = w.Write([]byte("png-bytes"))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
origHost, origToken := flag.Host, flag.Token
|
||||||
|
flag.Host, flag.Token = server.URL, "secret-token"
|
||||||
|
defer func() { flag.Host, flag.Token = origHost, origToken }()
|
||||||
|
|
||||||
|
raw, contentType, status, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("DownloadAttachment() error = %v", err)
|
||||||
|
}
|
||||||
|
if status != http.StatusOK {
|
||||||
|
t.Fatalf("DownloadAttachment() status = %d, want %d", status, http.StatusOK)
|
||||||
|
}
|
||||||
|
if contentType != "image/png" {
|
||||||
|
t.Fatalf("contentType = %q", contentType)
|
||||||
|
}
|
||||||
|
if string(raw) != "png-bytes" {
|
||||||
|
t.Fatalf("body = %q", string(raw))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDownloadAttachmentRejectsCrossOriginRedirect(t *testing.T) {
|
||||||
|
redirected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Fatalf("cross-origin redirect should not be followed: %s", r.URL.String())
|
||||||
|
}))
|
||||||
|
defer redirected.Close()
|
||||||
|
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Redirect(w, r, redirected.URL+"/attachments/uuid-1", http.StatusFound)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
origHost, origToken := flag.Host, flag.Token
|
||||||
|
flag.Host, flag.Token = server.URL, "secret-token"
|
||||||
|
defer func() { flag.Host, flag.Token = origHost, origToken }()
|
||||||
|
|
||||||
|
_, _, _, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for cross-origin redirect")
|
||||||
|
}
|
||||||
|
want := "do request: Get \"" + redirected.URL + "/attachments/uuid-1\": attachment redirect changed origin"
|
||||||
|
if err.Error() != want {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDownloadAttachmentRejectsSameOriginRedirectLoopAtHopLimit(t *testing.T) {
|
||||||
|
var serverURL string
|
||||||
|
redirects := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
redirects++
|
||||||
|
http.Redirect(w, r, serverURL+"/attachments/uuid-1", http.StatusFound)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
serverURL = server.URL
|
||||||
|
|
||||||
|
origHost := flag.Host
|
||||||
|
flag.Host = server.URL
|
||||||
|
defer func() { flag.Host = origHost }()
|
||||||
|
|
||||||
|
_, _, _, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected redirect limit error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "stopped after 10 redirects") {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if redirects != 10 {
|
||||||
|
t.Fatalf("redirects = %d, want 10", redirects)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteAttachmentStreamsBodyToFile(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "attachment.bin")
|
||||||
|
written, err := WriteAttachment(strings.NewReader(strings.Repeat("z", 64)), path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WriteAttachment() error = %v", err)
|
||||||
|
}
|
||||||
|
if written != 64 {
|
||||||
|
t.Fatalf("written = %d, want 64", written)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadFile() error = %v", err)
|
||||||
|
}
|
||||||
|
if string(data) != strings.Repeat("z", 64) {
|
||||||
|
t.Fatalf("body mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteAttachmentCreatesPrivateFile(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "attachment.bin")
|
||||||
|
|
||||||
|
if _, err := WriteAttachment(strings.NewReader("secret"), path); err != nil {
|
||||||
|
t.Fatalf("WriteAttachment() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Stat() error = %v", err)
|
||||||
|
}
|
||||||
|
if got := info.Mode().Perm() & 0o077; got != 0 {
|
||||||
|
t.Fatalf("permissions = %03o, want no group/other bits", info.Mode().Perm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteAttachmentTightensExistingFilePermissions(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "attachment.bin")
|
||||||
|
if err := os.WriteFile(path, []byte("public"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := WriteAttachment(strings.NewReader("secret"), path); err != nil {
|
||||||
|
t.Fatalf("WriteAttachment() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Stat() error = %v", err)
|
||||||
|
}
|
||||||
|
if got := info.Mode().Perm(); got != 0o600 {
|
||||||
|
t.Fatalf("permissions = %03o, want 600", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDownloadAttachmentErrorsOnNon2xx(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Error(w, "nope", http.StatusForbidden)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
origHost := flag.Host
|
||||||
|
flag.Host = server.URL
|
||||||
|
defer func() { flag.Host = origHost }()
|
||||||
|
|
||||||
|
_, _, status, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*")
|
||||||
|
if status != http.StatusForbidden {
|
||||||
|
t.Fatalf("status = %d, want %d", status, http.StatusForbidden)
|
||||||
|
}
|
||||||
|
var httpErr *HTTPError
|
||||||
|
if !errors.As(err, &httpErr) {
|
||||||
|
t.Fatalf("expected HTTPError, got %T", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttachmentHTTPClientHasNoTotalTimeout(t *testing.T) {
|
||||||
|
origin := &url.URL{Scheme: "https", Host: "example.com"}
|
||||||
|
|
||||||
|
client := attachmentHTTPClient(origin)
|
||||||
|
|
||||||
|
if client.Timeout != 0 {
|
||||||
|
t.Fatalf("Timeout = %v, want 0", client.Timeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
+151
-15
@@ -9,6 +9,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -34,6 +36,12 @@ func (e *HTTPError) Error() string {
|
|||||||
return fmt.Sprintf("request failed with status %d: %s", e.StatusCode, e.Body)
|
return fmt.Sprintf("request failed with status %d: %s", e.StatusCode, e.Body)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type AttachmentResponse struct {
|
||||||
|
Body io.ReadCloser
|
||||||
|
ContentType string
|
||||||
|
StatusCode int
|
||||||
|
}
|
||||||
|
|
||||||
func tokenFromContext(ctx context.Context) string {
|
func tokenFromContext(ctx context.Context) string {
|
||||||
if ctx != nil {
|
if ctx != nil {
|
||||||
if token, ok := ctx.Value(mcpContext.TokenContextKey).(string); ok && token != "" {
|
if token, ok := ctx.Value(mcpContext.TokenContextKey).(string); ok && token != "" {
|
||||||
@@ -75,6 +83,40 @@ func buildAPIURL(path string, query url.Values) (string, error) {
|
|||||||
return u.String(), nil
|
return u.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func buildAttachmentURL(attachmentPath string) (string, error) {
|
||||||
|
host := strings.TrimRight(flag.Host, "/")
|
||||||
|
if host == "" {
|
||||||
|
return "", errors.New("gitea host is empty")
|
||||||
|
}
|
||||||
|
baseURL, err := url.Parse(host)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if attachmentPath == "" {
|
||||||
|
return "", errors.New("attachment path is empty")
|
||||||
|
}
|
||||||
|
if strings.Contains(attachmentPath, "://") {
|
||||||
|
return "", errors.New("attachment path must not be a URL")
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(attachmentPath, "/attachments/") {
|
||||||
|
return "", errors.New("attachment path must start with /attachments/")
|
||||||
|
}
|
||||||
|
cleanPath := path.Clean(attachmentPath)
|
||||||
|
if !strings.HasPrefix(cleanPath, "/attachments/") {
|
||||||
|
return "", errors.New("attachment path must stay within /attachments/")
|
||||||
|
}
|
||||||
|
if cleanPath == "/attachments" || cleanPath == "/attachments/" {
|
||||||
|
return "", errors.New("attachment uuid is required")
|
||||||
|
}
|
||||||
|
joinedPath := strings.TrimRight(baseURL.Path, "/") + cleanPath
|
||||||
|
if joinedPath == "" {
|
||||||
|
joinedPath = cleanPath
|
||||||
|
}
|
||||||
|
baseURL.Path = joinedPath
|
||||||
|
baseURL.RawPath = joinedPath
|
||||||
|
return baseURL.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
// DoJSON performs an API request and decodes a JSON response into respOut (if non-nil).
|
// DoJSON performs an API request and decodes a JSON response into respOut (if non-nil).
|
||||||
// It returns the HTTP status code.
|
// It returns the HTTP status code.
|
||||||
func DoJSON(ctx context.Context, method, path string, query url.Values, body, respOut any) (int, error) {
|
func DoJSON(ctx context.Context, method, path string, query url.Values, body, respOut any) (int, error) {
|
||||||
@@ -91,45 +133,142 @@ func DoJSON(ctx context.Context, method, path string, query url.Values, body, re
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
|
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("create request: %w", err)
|
return 0, fmt.Errorf("create request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
token := tokenFromContext(ctx)
|
token := tokenFromContext(ctx)
|
||||||
if token != "" {
|
if token != "" {
|
||||||
req.Header.Set("Authorization", "token "+token)
|
req.Header.Set("Authorization", "token "+token)
|
||||||
}
|
}
|
||||||
req.Header.Set("Accept", "application/json")
|
|
||||||
if body != nil {
|
if body != nil {
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
}
|
}
|
||||||
|
if respOut != nil {
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
}
|
||||||
|
|
||||||
client := restHTTPClient()
|
resp, err := restHTTPClient().Do(req)
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("do request: %w", err)
|
return 0, fmt.Errorf("do request: %w", err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
bodySnippet, _ := io.ReadAll(io.LimitReader(resp.Body, errBodySnippetSize))
|
bodySnippet, err := io.ReadAll(io.LimitReader(resp.Body, errBodySnippetSize+1))
|
||||||
|
if err != nil {
|
||||||
|
return resp.StatusCode, fmt.Errorf("read response: %w", err)
|
||||||
|
}
|
||||||
|
if len(bodySnippet) > errBodySnippetSize {
|
||||||
|
bodySnippet = bodySnippet[:errBodySnippetSize]
|
||||||
|
}
|
||||||
return resp.StatusCode, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))}
|
return resp.StatusCode, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))}
|
||||||
}
|
}
|
||||||
|
|
||||||
if respOut == nil {
|
if respOut == nil {
|
||||||
_, _ = io.Copy(io.Discard, resp.Body) // best-effort
|
_, _ = io.Copy(io.Discard, resp.Body)
|
||||||
return resp.StatusCode, nil
|
return resp.StatusCode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := json.NewDecoder(resp.Body).Decode(respOut); err != nil {
|
if err := json.NewDecoder(resp.Body).Decode(respOut); err != nil {
|
||||||
return resp.StatusCode, fmt.Errorf("decode response: %w", err)
|
return resp.StatusCode, fmt.Errorf("decode response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return resp.StatusCode, nil
|
return resp.StatusCode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func attachmentHTTPClient(origin *url.URL) *http.Client {
|
||||||
|
return &http.Client{
|
||||||
|
Transport: sharedTransport(),
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
if err := checkRedirect(req, via); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if req.URL.Scheme != origin.Scheme || req.URL.Host != origin.Host {
|
||||||
|
return errors.New("attachment redirect changed origin")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func OpenAttachment(ctx context.Context, attachmentPath, accept string) (*AttachmentResponse, error) {
|
||||||
|
u, err := buildAttachmentURL(attachmentPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
origin, err := url.Parse(u)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create request: %w", err)
|
||||||
|
}
|
||||||
|
token := tokenFromContext(ctx)
|
||||||
|
if token != "" {
|
||||||
|
req.Header.Set("Authorization", "token "+token)
|
||||||
|
}
|
||||||
|
if accept != "" {
|
||||||
|
req.Header.Set("Accept", accept)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := attachmentHTTPClient(origin).Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("do request: %w", err)
|
||||||
|
}
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
defer resp.Body.Close()
|
||||||
|
bodySnippet, readErr := io.ReadAll(io.LimitReader(resp.Body, errBodySnippetSize+1))
|
||||||
|
if readErr != nil {
|
||||||
|
return nil, fmt.Errorf("read response: %w", readErr)
|
||||||
|
}
|
||||||
|
if len(bodySnippet) > errBodySnippetSize {
|
||||||
|
bodySnippet = bodySnippet[:errBodySnippetSize]
|
||||||
|
}
|
||||||
|
return nil, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))}
|
||||||
|
}
|
||||||
|
return &AttachmentResponse{Body: resp.Body, ContentType: resp.Header.Get("Content-Type"), StatusCode: resp.StatusCode}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownloadAttachment downloads attachment bytes from a same-host attachment path.
|
||||||
|
func DownloadAttachment(ctx context.Context, attachmentPath, accept string) ([]byte, string, int, error) {
|
||||||
|
resp, err := OpenAttachment(ctx, attachmentPath, accept)
|
||||||
|
if err != nil {
|
||||||
|
var httpErr *HTTPError
|
||||||
|
if errors.As(err, &httpErr) {
|
||||||
|
return nil, "", httpErr.StatusCode, err
|
||||||
|
}
|
||||||
|
return nil, "", 0, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBytes, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", resp.StatusCode, fmt.Errorf("read response: %w", err)
|
||||||
|
}
|
||||||
|
return respBytes, resp.ContentType, resp.StatusCode, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteAttachment(body io.Reader, outputPath string) (int64, error) {
|
||||||
|
file, err := os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
if err := file.Chmod(0o600); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
written, err := io.Copy(file, body)
|
||||||
|
if err != nil {
|
||||||
|
return written, err
|
||||||
|
}
|
||||||
|
return written, file.Close()
|
||||||
|
}
|
||||||
|
|
||||||
// DoBytes performs an API request and returns the raw response bytes.
|
// DoBytes performs an API request and returns the raw response bytes.
|
||||||
// It returns the HTTP status code.
|
|
||||||
func DoBytes(ctx context.Context, method, path string, query url.Values, body any, accept string) ([]byte, int, error) {
|
func DoBytes(ctx context.Context, method, path string, query url.Values, body any, accept string) ([]byte, int, error) {
|
||||||
var bodyReader io.Reader
|
var bodyReader io.Reader
|
||||||
if body != nil {
|
if body != nil {
|
||||||
@@ -144,24 +283,23 @@ func DoBytes(ctx context.Context, method, path string, query url.Values, body an
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
|
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, fmt.Errorf("create request: %w", err)
|
return nil, 0, fmt.Errorf("create request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
token := tokenFromContext(ctx)
|
token := tokenFromContext(ctx)
|
||||||
if token != "" {
|
if token != "" {
|
||||||
req.Header.Set("Authorization", "token "+token)
|
req.Header.Set("Authorization", "token "+token)
|
||||||
}
|
}
|
||||||
if accept != "" {
|
|
||||||
req.Header.Set("Accept", accept)
|
|
||||||
}
|
|
||||||
if body != nil {
|
if body != nil {
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
}
|
}
|
||||||
|
if accept != "" {
|
||||||
|
req.Header.Set("Accept", accept)
|
||||||
|
}
|
||||||
|
|
||||||
client := restHTTPClient()
|
resp, err := restHTTPClient().Do(req)
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, fmt.Errorf("do request: %w", err)
|
return nil, 0, fmt.Errorf("do request: %w", err)
|
||||||
}
|
}
|
||||||
@@ -171,7 +309,6 @@ func DoBytes(ctx context.Context, method, path string, query url.Values, body an
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, resp.StatusCode, fmt.Errorf("read response: %w", err)
|
return nil, resp.StatusCode, fmt.Errorf("read response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
bodySnippet := respBytes
|
bodySnippet := respBytes
|
||||||
if len(bodySnippet) > errBodySnippetSize {
|
if len(bodySnippet) > errBodySnippetSize {
|
||||||
@@ -179,6 +316,5 @@ func DoBytes(ctx context.Context, method, path string, query url.Values, body an
|
|||||||
}
|
}
|
||||||
return nil, resp.StatusCode, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))}
|
return nil, resp.StatusCode, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))}
|
||||||
}
|
}
|
||||||
|
|
||||||
return respBytes, resp.StatusCode, nil
|
return respBytes, resp.StatusCode, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,11 @@ package gitea
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
mcpContext "gitea.com/gitea/gitea-mcp/pkg/context"
|
mcpContext "gitea.com/gitea/gitea-mcp/pkg/context"
|
||||||
@@ -28,3 +33,32 @@ func TestTokenFromContext(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDoJSON_LimitsErrorResponseBody(t *testing.T) {
|
||||||
|
payload := strings.Repeat("x", errBodySnippetSize+100)
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
_, _ = io.WriteString(w, payload)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
origHost := flag.Host
|
||||||
|
defer func() { flag.Host = origHost }()
|
||||||
|
flag.Host = srv.URL
|
||||||
|
|
||||||
|
status, err := DoJSON(context.Background(), http.MethodGet, "repos/owner/repo", nil, nil, nil)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error")
|
||||||
|
}
|
||||||
|
if status != http.StatusBadRequest {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
var httpErr *HTTPError
|
||||||
|
if !errors.As(err, &httpErr) {
|
||||||
|
t.Fatalf("expected HTTPError, got %T", err)
|
||||||
|
}
|
||||||
|
if len(httpErr.Body) != errBodySnippetSize {
|
||||||
|
t.Fatalf("expected body length %d, got %d", errBodySnippetSize, len(httpErr.Body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+68
-15
@@ -11,17 +11,24 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Tool struct {
|
type Tool struct {
|
||||||
|
scope string
|
||||||
write []server.ServerTool
|
write []server.ServerTool
|
||||||
read []server.ServerTool
|
read []server.ServerTool
|
||||||
}
|
}
|
||||||
|
|
||||||
func New() *Tool {
|
func New(scope string) *Tool {
|
||||||
return &Tool{
|
return &Tool{
|
||||||
|
scope: scope,
|
||||||
write: make([]server.ServerTool, 0, 100),
|
write: make([]server.ServerTool, 0, 100),
|
||||||
read: make([]server.ServerTool, 0, 100),
|
read: make([]server.ServerTool, 0, 100),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Scope returns the canonical scope name this domain of tools was registered under.
|
||||||
|
func (t *Tool) Scope() string {
|
||||||
|
return t.scope
|
||||||
|
}
|
||||||
|
|
||||||
func (t *Tool) RegisterWrite(s server.ServerTool) {
|
func (t *Tool) RegisterWrite(s server.ServerTool) {
|
||||||
t.write = append(t.write, s)
|
t.write = append(t.write, s)
|
||||||
}
|
}
|
||||||
@@ -30,31 +37,67 @@ func (t *Tool) RegisterRead(s server.ServerTool) {
|
|||||||
t.read = append(t.read, s)
|
t.read = append(t.read, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadTools returns the read-only tools registered on this domain, ignoring
|
||||||
|
// the read-only and allowlist flags that Tools applies.
|
||||||
|
func (t *Tool) ReadTools() []server.ServerTool {
|
||||||
|
return t.read
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteTools returns the write tools registered on this domain, ignoring the
|
||||||
|
// read-only and allowlist flags that Tools applies.
|
||||||
|
func (t *Tool) WriteTools() []server.ServerTool {
|
||||||
|
return t.write
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tools returns the tools registered on this domain after applying the
|
||||||
|
// read-only filter and the scope/tool allowlists (union semantics: a tool is
|
||||||
|
// kept if its domain's scope is in AllowedScopes OR its name is in
|
||||||
|
// AllowedTools). With no allowlists set, all tools pass through unchanged.
|
||||||
func (t *Tool) Tools() []server.ServerTool {
|
func (t *Tool) Tools() []server.ServerTool {
|
||||||
all := make([]server.ServerTool, 0, len(t.write)+len(t.read))
|
all := make([]server.ServerTool, 0, len(t.write)+len(t.read))
|
||||||
if !flag.ReadOnly {
|
if !flag.ReadOnly {
|
||||||
all = append(all, t.write...)
|
all = append(all, t.write...)
|
||||||
}
|
}
|
||||||
all = append(all, t.read...)
|
all = append(all, t.read...)
|
||||||
if len(flag.AllowedTools) == 0 {
|
if len(flag.AllowedScopes) == 0 && len(flag.AllowedTools) == 0 {
|
||||||
return all
|
return all
|
||||||
}
|
}
|
||||||
|
_, scopeAllowed := flag.AllowedScopes[t.scope]
|
||||||
filtered := make([]server.ServerTool, 0, len(all))
|
filtered := make([]server.ServerTool, 0, len(all))
|
||||||
for _, st := range all {
|
for _, st := range all {
|
||||||
if _, ok := flag.AllowedTools[st.Tool.Name]; ok {
|
_, toolAllowed := flag.AllowedTools[st.Tool.Name]
|
||||||
|
if scopeAllowed || toolAllowed {
|
||||||
filtered = append(filtered, st)
|
filtered = append(filtered, st)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return filtered
|
return filtered
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// warnUnmatched logs the names present in allowlist but absent from known,
|
||||||
|
// via logUnmatched, so WarnUnmatchedAllowedTools and WarnUnmatchedAllowedScopes
|
||||||
|
// share the same "collect, sort, no-op when empty" logic and can't drift.
|
||||||
|
// No-op if allowlist is empty or every name in it is known.
|
||||||
|
func warnUnmatched(allowlist, known map[string]struct{}, logUnmatched func(unmatched []string)) {
|
||||||
|
if len(allowlist) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var unmatched []string
|
||||||
|
for name := range allowlist {
|
||||||
|
if _, ok := known[name]; !ok {
|
||||||
|
unmatched = append(unmatched, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(unmatched) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
slices.Sort(unmatched)
|
||||||
|
logUnmatched(unmatched)
|
||||||
|
}
|
||||||
|
|
||||||
// WarnUnmatchedAllowedTools logs any names in flag.AllowedTools that don't
|
// WarnUnmatchedAllowedTools logs any names in flag.AllowedTools that don't
|
||||||
// match a tool registered on any of the given domains. No-op if the allowlist
|
// match a tool registered on any of the given domains. No-op if the allowlist
|
||||||
// is empty.
|
// is empty.
|
||||||
func WarnUnmatchedAllowedTools(domains ...*Tool) {
|
func WarnUnmatchedAllowedTools(domains ...*Tool) {
|
||||||
if len(flag.AllowedTools) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
known := map[string]struct{}{}
|
known := map[string]struct{}{}
|
||||||
for _, d := range domains {
|
for _, d := range domains {
|
||||||
for _, st := range d.read {
|
for _, st := range d.read {
|
||||||
@@ -64,15 +107,25 @@ func WarnUnmatchedAllowedTools(domains ...*Tool) {
|
|||||||
known[st.Tool.Name] = struct{}{}
|
known[st.Tool.Name] = struct{}{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var unmatched []string
|
warnUnmatched(flag.AllowedTools, known, func(unmatched []string) {
|
||||||
for name := range flag.AllowedTools {
|
log.Warnf("Unknown tools in --tools allowlist (ignored): %s", strings.Join(unmatched, ", "))
|
||||||
if _, ok := known[name]; !ok {
|
})
|
||||||
unmatched = append(unmatched, name)
|
}
|
||||||
|
|
||||||
|
// WarnUnmatchedAllowedScopes logs any names in flag.AllowedScopes that don't
|
||||||
|
// match the scope of any of the given domains. No-op if the allowlist is
|
||||||
|
// empty.
|
||||||
|
func WarnUnmatchedAllowedScopes(domains ...*Tool) {
|
||||||
|
knownSet := map[string]struct{}{}
|
||||||
|
known := make([]string, 0, len(domains))
|
||||||
|
for _, d := range domains {
|
||||||
|
if _, ok := knownSet[d.scope]; !ok {
|
||||||
|
knownSet[d.scope] = struct{}{}
|
||||||
|
known = append(known, d.scope)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(unmatched) == 0 {
|
warnUnmatched(flag.AllowedScopes, knownSet, func(unmatched []string) {
|
||||||
return
|
slices.Sort(known)
|
||||||
}
|
log.Warnf("Unknown scopes in --scope allowlist (ignored): %s. Valid scopes: %s", strings.Join(unmatched, ", "), strings.Join(known, ", "))
|
||||||
slices.Sort(unmatched)
|
})
|
||||||
log.Warnf("Unknown tools in --tools allowlist (ignored): %s", strings.Join(unmatched, ", "))
|
|
||||||
}
|
}
|
||||||
|
|||||||
+128
-1
@@ -83,7 +83,7 @@ func TestTools(t *testing.T) {
|
|||||||
flag.ReadOnly = tt.readOnly
|
flag.ReadOnly = tt.readOnly
|
||||||
flag.AllowedTools = tt.allowed
|
flag.AllowedTools = tt.allowed
|
||||||
|
|
||||||
tr := New()
|
tr := New("scope1")
|
||||||
for _, n := range tt.read {
|
for _, n := range tt.read {
|
||||||
tr.RegisterRead(makeTool(n))
|
tr.RegisterRead(makeTool(n))
|
||||||
}
|
}
|
||||||
@@ -98,3 +98,130 @@ func TestTools(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestToolsScopeFiltering(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
toolScope string
|
||||||
|
readOnly bool
|
||||||
|
allowedScopes map[string]struct{}
|
||||||
|
allowedTools map[string]struct{}
|
||||||
|
read []string
|
||||||
|
write []string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "no scope or tool filters returns all",
|
||||||
|
toolScope: "repository",
|
||||||
|
read: []string{"r1"},
|
||||||
|
write: []string{"w1"},
|
||||||
|
want: []string{"w1", "r1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "matching scope keeps everything",
|
||||||
|
toolScope: "repository",
|
||||||
|
allowedScopes: map[string]struct{}{"repository": {}},
|
||||||
|
read: []string{"r1"},
|
||||||
|
write: []string{"w1"},
|
||||||
|
want: []string{"w1", "r1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "non-matching scope drops everything not in allowed tools",
|
||||||
|
toolScope: "repository",
|
||||||
|
allowedScopes: map[string]struct{}{"file": {}},
|
||||||
|
read: []string{"r1"},
|
||||||
|
write: []string{"w1"},
|
||||||
|
want: []string{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "tools-only allowlist behaves as before scopes existed",
|
||||||
|
toolScope: "repository",
|
||||||
|
allowedTools: map[string]struct{}{"r1": {}},
|
||||||
|
read: []string{"r1", "r2"},
|
||||||
|
write: []string{"w1"},
|
||||||
|
want: []string{"r1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "scope and tools allowlists are unioned",
|
||||||
|
toolScope: "repository",
|
||||||
|
allowedScopes: map[string]struct{}{"file": {}},
|
||||||
|
allowedTools: map[string]struct{}{"r1": {}},
|
||||||
|
read: []string{"r1", "r2"},
|
||||||
|
write: []string{"w1"},
|
||||||
|
want: []string{"r1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "matching scope combined with read-only drops write entries",
|
||||||
|
toolScope: "repository",
|
||||||
|
readOnly: true,
|
||||||
|
allowedScopes: map[string]struct{}{"repository": {}},
|
||||||
|
read: []string{"r1"},
|
||||||
|
write: []string{"w1"},
|
||||||
|
want: []string{"r1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown scope name matches nothing",
|
||||||
|
toolScope: "repository",
|
||||||
|
allowedScopes: map[string]struct{}{"unknown_scope": {}},
|
||||||
|
read: []string{"r1"},
|
||||||
|
write: []string{"w1"},
|
||||||
|
want: []string{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
origRO, origAllowScopes, origAllowTools := flag.ReadOnly, flag.AllowedScopes, flag.AllowedTools
|
||||||
|
t.Cleanup(func() {
|
||||||
|
flag.ReadOnly, flag.AllowedScopes, flag.AllowedTools = origRO, origAllowScopes, origAllowTools
|
||||||
|
})
|
||||||
|
flag.ReadOnly = tt.readOnly
|
||||||
|
flag.AllowedScopes = tt.allowedScopes
|
||||||
|
flag.AllowedTools = tt.allowedTools
|
||||||
|
|
||||||
|
tr := New(tt.toolScope)
|
||||||
|
for _, n := range tt.read {
|
||||||
|
tr.RegisterRead(makeTool(n))
|
||||||
|
}
|
||||||
|
for _, n := range tt.write {
|
||||||
|
tr.RegisterWrite(makeTool(n))
|
||||||
|
}
|
||||||
|
|
||||||
|
got := names(tr.Tools())
|
||||||
|
if !slices.Equal(got, tt.want) {
|
||||||
|
t.Errorf("Tools() = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScope(t *testing.T) {
|
||||||
|
tr := New("repository")
|
||||||
|
if got := tr.Scope(); got != "repository" {
|
||||||
|
t.Errorf("Scope() = %q, want %q", got, "repository")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWarnUnmatchedAllowedScopes(t *testing.T) {
|
||||||
|
origAllowScopes := flag.AllowedScopes
|
||||||
|
t.Cleanup(func() {
|
||||||
|
flag.AllowedScopes = origAllowScopes
|
||||||
|
})
|
||||||
|
|
||||||
|
repoTool := New("repository")
|
||||||
|
fileTool := New("file")
|
||||||
|
|
||||||
|
t.Run("empty allowlist is a no-op", func(t *testing.T) {
|
||||||
|
flag.AllowedScopes = nil
|
||||||
|
WarnUnmatchedAllowedScopes(repoTool, fileTool)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("known scopes produce no warning", func(t *testing.T) {
|
||||||
|
flag.AllowedScopes = map[string]struct{}{"repository": {}, "file": {}}
|
||||||
|
WarnUnmatchedAllowedScopes(repoTool, fileTool)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("unknown scope is tolerated", func(t *testing.T) {
|
||||||
|
flag.AllowedScopes = map[string]struct{}{"not_a_real_scope": {}}
|
||||||
|
WarnUnmatchedAllowedScopes(repoTool, fileTool)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user