gitea-mcp: 初次落地 Gitea MCP Server (.NET 10, V1 only-read)
Build Docker Image / build (push) Failing after 5m41s
Build Docker Image / deploy (push) Has been skipped

把 Gitea (git.zhengchentao.win) 通过 MCP 暴露给 Claude.ai:列 repo、读代码、看 commits / issues / PR / orgs / packages / actions。
设计文档见 vault Coding/gitea-mcp/gitea-mcp 设计.md。
代码模板复用 obsidian-mcp(.NET 10 + ModelContextProtocol SDK + JwtBearer)。

19 个只读 Tool(全部 scope=read:gitea):

Repo / 文件:
- list_repos / read_repo
- list_tree(max_entries=500 防爆)
- read_file(max_bytes=1MB,超出 truncated=true)
- search_code(走 /repos/search-code,indexer 未启用时返回结构化错误说明)

分支 / 提交:
- list_branches / list_commits / read_commit(diff 文件数限 50)

Issue / PR:
- list_issues / read_issue(含评论)
- list_pulls / read_pull(含评论 + 改动文件列表)

Org / Package(用户额外授权 read:organization + read:package):
- list_orgs / read_org
- list_packages / read_package

Gitea Actions(运维友好):
- list_workflow_runs / read_run_log

技术栈:
- .NET 10 + ModelContextProtocol SDK 1.0
- HttpClientFactory + Microsoft.Extensions.Http.Resilience(指数 backoff,5xx/429/网络错误重试)
- JwtBearer (HS256, Current+Previous fallback, MapInboundClaims=false)
- aud=gitea, scope=read:gitea, iss=https://auth.zhengchentao.win

Gitea API client:
- Authorization: token <PAT> (admin PAT,仅 read scope)
- BaseUrl=https://git.zhengchentao.win
- 错误映射:401/403 → UnauthorizedAccessException,404 → KeyNotFoundException,5xx → InvalidOperationException
- RepoBlacklist 黑名单(owner/repo 精确匹配,默认空)

部署:
- Dockerfile multi-stage,COPY --chown,non-root user
- .gitea/workflows/build-image.yml:build + deploy 双 job,buildkit v0.13.2
- 容器内 :8080,宿主端口 9092
- 子域名 git-mcp.zhengchentao.win(区别于 Gitea 本体 git.zhengchentao.win)

测试:6/6 单测过(GiteaRepoFilter 黑名单匹配)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-06 01:32:42 +08:00
commit c7fa6aeb7f
38 changed files with 2675 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
using GiteaMcp.Services;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>Gitea Actions Toollist_workflow_runs / read_run_log</summary>
[McpServerToolType]
public class ActionsTools(
GiteaApiClient gitea,
GiteaRepoFilter filter)
{
[McpServerTool]
[Description(
"List recent Gitea Actions workflow runs for a repository. " +
"Filter by branch name or run status (queued/in_progress/success/failure/cancelled/skipped). " +
"Returns: run ID, workflow name, triggering event, branch, status, conclusion, actor, and timestamps. " +
"Use read_run_log to get the full log output of a specific run or job.")]
public async Task<object> list_workflow_runs(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Filter by branch name. Optional.")] string? branch = null,
[Description("Filter by status: 'queued', 'in_progress', 'success', 'failure', 'cancelled', 'skipped'. Optional.")] string? status = null,
[Description("Max runs to return. Default 30.")] int? limit = null,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var lim = Math.Min(limit ?? 30, 100);
var result = await gitea.GetWorkflowRunsAsync(owner, repo, branch, status, lim, ct);
return new
{
total = result.TotalCount,
runs = result.WorkflowRuns.Select(r => new
{
id = r.Id,
name = r.Name,
@event = r.Event,
branch = r.HeadBranch,
sha = r.HeadSha,
status = r.Status,
conclusion = r.Conclusion,
actor = r.Actor?.Login,
html_url = r.HtmlUrl,
created_at = r.CreatedAt,
updated_at = r.UpdatedAt,
}).ToList(),
};
}
[McpServerTool]
[Description(
"Get detailed info and log output for a specific Gitea Actions workflow run. " +
"Returns: run overview (status, conclusion, timing) + all jobs with their status. " +
"Log output is truncated to 1MB; long logs will have '[...log truncated...]' appended. " +
"When job_id is provided, fetches that specific job's log; otherwise fetches the run-level log. " +
"Use list_workflow_runs to find the run_id.")]
public async Task<object> read_run_log(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Workflow run ID (from list_workflow_runs).")] long run_id,
[Description("Specific job ID to fetch logs for. Omit to get the run-level log.")] long? job_id = null,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var runTask = gitea.GetWorkflowRunAsync(owner, repo, run_id, ct);
var jobsTask = gitea.GetRunJobsAsync(owner, repo, run_id, ct);
var logTask = gitea.GetRunLogAsync(owner, repo, run_id, job_id, ct: ct);
await Task.WhenAll(runTask, jobsTask, logTask);
var run = await runTask;
var jobList = await jobsTask;
var log = await logTask;
return new
{
run = new
{
id = run.Id,
name = run.Name,
@event = run.Event,
branch = run.HeadBranch,
sha = run.HeadSha,
status = run.Status,
conclusion = run.Conclusion,
actor = run.Actor?.Login,
html_url = run.HtmlUrl,
created_at = run.CreatedAt,
updated_at = run.UpdatedAt,
},
jobs = jobList.WorkflowJobs.Select(j => new
{
id = j.Id,
name = j.Name,
status = j.Status,
conclusion = j.Conclusion,
started_at = j.StartedAt,
completed_at = j.CompletedAt,
}).ToList(),
log,
};
}
}
+121
View File
@@ -0,0 +1,121 @@
using GiteaMcp.Services;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>分支与 commit Toollist_branches / list_commits / read_commit</summary>
[McpServerToolType]
public class BranchCommitTools(
GiteaApiClient gitea,
GiteaRepoFilter filter)
{
[McpServerTool]
[Description(
"List all branches in a Gitea repository with their latest commit info. " +
"Returns: branch name, protected flag, last commit SHA, message, timestamp, and author. " +
"Use this to discover available branches before calling list_commits or read_file with a specific ref.")]
public async Task<object> list_branches(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var branches = await gitea.GetBranchesAsync(owner, repo, ct);
return branches.Select(b => new
{
name = b.Name,
@protected = b.Protected,
last_commit = b.Commit == null ? null : new
{
sha = b.Commit.Id,
message = b.Commit.Message,
timestamp = b.Commit.Timestamp,
author = b.Commit.Author?.Name,
},
}).ToList();
}
[McpServerTool]
[Description(
"List recent commits in a Gitea repository. " +
"Returns: SHA (short+full), commit message, author, and timestamp. " +
"Use ref to specify a branch or tag; use since (ISO 8601 date) to filter by date. " +
"Default returns up to 30 commits. Good for 'what changed recently' questions.")]
public async Task<object> list_commits(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Branch, tag, or SHA. Defaults to the default branch.")] string? @ref = null,
[Description("Only commits after this date (ISO 8601, e.g. '2026-04-01T00:00:00Z'). Optional.")] string? since = null,
[Description("Max commits to return. Default 30.")] int? limit = null,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var lim = Math.Min(limit ?? 30, 100);
var commits = await gitea.GetCommitsAsync(owner, repo, @ref, since, lim, ct);
return commits.Select(c => new
{
sha = c.Sha,
sha_short = c.Sha.Length >= 8 ? c.Sha[..8] : c.Sha,
message = c.Commit?.Message,
author = c.Commit?.Author?.Name,
author_email = c.Commit?.Author?.Email,
timestamp = c.Commit?.Author?.Date ?? c.Created,
}).ToList();
}
[McpServerTool]
[Description(
"Get full details of a single commit: message, author, stats, and per-file diff. " +
"Files are limited to max_files=50; when truncated=true, some files are omitted. " +
"Patch (diff text) is included per file — useful for code review or understanding specific changes. " +
"Use list_commits first to obtain a SHA.")]
public async Task<object> read_commit(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Full or abbreviated commit SHA.")] string sha,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
const int MaxFiles = 50;
var commit = await gitea.GetCommitAsync(owner, repo, sha, ct);
var files = commit.Files ?? [];
bool truncated = files.Count > MaxFiles;
if (truncated) files = files.Take(MaxFiles).ToList();
return new
{
sha = commit.Sha,
message = commit.Commit?.Message,
author = commit.Commit?.Author?.Name,
author_email = commit.Commit?.Author?.Email,
authored_at = commit.Commit?.Author?.Date,
committer = commit.Commit?.Committer?.Name,
committed_at = commit.Commit?.Committer?.Date ?? commit.Created,
stats = commit.Stats == null ? null : new
{
total = commit.Stats.Total,
additions = commit.Stats.Additions,
deletions = commit.Stats.Deletions,
},
files_truncated = truncated,
files = files.Select(f => new
{
filename = f.Filename,
status = f.Status,
additions = f.Additions,
deletions = f.Deletions,
changes = f.Changes,
patch = f.Patch,
}).ToList(),
};
}
}
+89
View File
@@ -0,0 +1,89 @@
using GiteaMcp.Services;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>Issue Toollist_issues / read_issue</summary>
[McpServerToolType]
public class IssueTools(
GiteaApiClient gitea,
GiteaRepoFilter filter)
{
[McpServerTool]
[Description(
"List issues in a Gitea repository. " +
"state can be 'open' (default), 'closed', or 'all'. " +
"Returns: issue number, title, state, labels, assignees, created_at, comment count, and URL. " +
"Use read_issue to get the full body and comments of a specific issue.")]
public async Task<object> list_issues(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Filter by state: 'open', 'closed', or 'all'. Default 'open'.")] string? state = null,
[Description("Max issues to return. Default 30.")] int? limit = null,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var st = state ?? "open";
var lim = Math.Min(limit ?? 30, 50);
var issues = await gitea.GetIssuesAsync(owner, repo, st, lim, ct);
return issues.Select(i => new
{
number = i.Number,
title = i.Title,
state = i.State,
html_url = i.HtmlUrl,
author = i.User?.Login,
labels = i.Labels?.Select(l => l.Name).ToList() ?? [],
assignees = i.Assignees?.Select(a => a.Login).ToList() ?? [],
comments = i.Comments,
created_at = i.CreatedAt,
updated_at = i.UpdatedAt,
closed_at = i.ClosedAt,
}).ToList();
}
[McpServerTool]
[Description(
"Get the full body and all comments of a specific Gitea issue. " +
"Use list_issues first to find the issue number. " +
"Returns: title, body (Markdown), state, labels, and all comment texts with authors and timestamps.")]
public async Task<object> read_issue(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Issue number (integer, e.g. 42).")] int number,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var issue = await gitea.GetIssueAsync(owner, repo, number, ct);
var comments = await gitea.GetIssueCommentsAsync(owner, repo, number, ct);
return new
{
number = issue.Number,
title = issue.Title,
body = issue.Body,
state = issue.State,
html_url = issue.HtmlUrl,
author = issue.User?.Login,
labels = issue.Labels?.Select(l => l.Name).ToList() ?? [],
assignees = issue.Assignees?.Select(a => a.Login).ToList() ?? [],
created_at = issue.CreatedAt,
updated_at = issue.UpdatedAt,
closed_at = issue.ClosedAt,
comments = comments.Select(c => new
{
id = c.Id,
author = c.User?.Login,
body = c.Body,
created_at = c.CreatedAt,
updated_at = c.UpdatedAt,
}).ToList(),
};
}
}
+56
View File
@@ -0,0 +1,56 @@
using GiteaMcp.Services;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>Organization Toollist_orgs / read_org</summary>
[McpServerToolType]
public class OrgTools(GiteaApiClient gitea)
{
[McpServerTool]
[Description(
"List all Gitea organizations visible to the admin token. " +
"Returns: org name, full name, description, visibility, and website. " +
"Use read_org to get repo/member counts for a specific org. " +
"Tip: after listing orgs, call list_repos with owner=<org_name> to see that org's repos.")]
public async Task<object> list_orgs(
[Description("Max orgs to return. Default 50.")] int? limit = null,
CancellationToken ct = default)
{
var lim = Math.Min(limit ?? 50, 50);
var orgs = await gitea.GetOrgsAsync(lim, ct);
return orgs.Select(o => new
{
name = o.Name,
full_name = o.FullName,
description = o.Description,
website = o.Website,
location = o.Location,
visibility = o.Visibility,
}).ToList();
}
[McpServerTool]
[Description(
"Get detailed information about a specific Gitea organization: " +
"description, website, location, and visibility setting. " +
"Use list_repos with owner=<name> to see the org's repositories.")]
public async Task<object> read_org(
[Description("Organization name (login).")] string name,
CancellationToken ct = default)
{
var org = await gitea.GetOrgAsync(name, ct);
return new
{
name = org.Name,
full_name = org.FullName,
description = org.Description,
website = org.Website,
location = org.Location,
visibility = org.Visibility,
};
}
}
+61
View File
@@ -0,0 +1,61 @@
using GiteaMcp.Services;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>Package Registry Toollist_packages / read_package</summary>
[McpServerToolType]
public class PackageTools(GiteaApiClient gitea)
{
[McpServerTool]
[Description(
"List packages in Gitea's built-in package registry for a given owner (user or org). " +
"Supports all package types: container (Docker/OCI), generic, npm, pypi, maven, nuget, etc. " +
"Returns: package name, type, version, creator, and creation date. " +
"Use read_package to get detailed metadata (e.g. OCI manifest digest for container images).")]
public async Task<object> list_packages(
[Description("Owner (user login or org name) whose packages to list.")] string owner,
[Description("Package type filter: 'container', 'generic', 'npm', 'pypi', 'maven', 'nuget', etc. Omit for all types.")] string? type = null,
[Description("Max packages to return. Default 50.")] int? limit = null,
CancellationToken ct = default)
{
var lim = Math.Min(limit ?? 50, 50);
var packages = await gitea.GetPackagesAsync(owner, type, lim, ct);
return packages.Select(p => new
{
owner = p.Owner?.Login,
name = p.Name,
type = p.Type,
version = p.Version,
creator = p.Creator?.Login,
created = p.Created,
}).ToList();
}
[McpServerTool]
[Description(
"Get metadata for a specific package version in Gitea's package registry. " +
"For container images, this includes the OCI manifest digest and image details. " +
"Use list_packages to discover available packages and their versions.")]
public async Task<object> read_package(
[Description("Owner (user login or org name).")] string owner,
[Description("Package type: 'container', 'generic', 'npm', etc.")] string type,
[Description("Package name.")] string name,
[Description("Package version string (e.g. 'latest', '1.0.0', 'main').")] string version,
CancellationToken ct = default)
{
var pkg = await gitea.GetPackageAsync(owner, type, name, version, ct);
return new
{
owner = pkg.Owner?.Login,
name = pkg.Name,
type = pkg.Type,
version = pkg.Version,
creator = pkg.Creator?.Login,
created = pkg.Created,
};
}
}
+110
View File
@@ -0,0 +1,110 @@
using GiteaMcp.Services;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>Pull Request Toollist_pulls / read_pull</summary>
[McpServerToolType]
public class PullTools(
GiteaApiClient gitea,
GiteaRepoFilter filter)
{
[McpServerTool]
[Description(
"List pull requests in a Gitea repository. " +
"state: 'open' (default), 'closed', or 'all'. " +
"Returns: PR number, title, state, head/base branches, merged status, labels, and URL. " +
"Use read_pull to get the full body, review comments, and changed files list.")]
public async Task<object> list_pulls(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Filter by state: 'open', 'closed', or 'all'. Default 'open'.")] string? state = null,
[Description("Max PRs to return. Default 30.")] int? limit = null,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var st = state ?? "open";
var lim = Math.Min(limit ?? 30, 50);
var pulls = await gitea.GetPullsAsync(owner, repo, st, lim, ct);
return pulls.Select(p => new
{
number = p.Number,
title = p.Title,
state = p.State,
html_url = p.HtmlUrl,
author = p.User?.Login,
head = p.Head?.Ref,
base_branch = p.Base?.Ref,
merged = p.Merged,
labels = p.Labels?.Select(l => l.Name).ToList() ?? [],
created_at = p.CreatedAt,
updated_at = p.UpdatedAt,
merged_at = p.MergedAt,
}).ToList();
}
[McpServerTool]
[Description(
"Get full details of a specific pull request: body, review comments, and list of changed files. " +
"Changed files include filename, status (added/modified/removed), and line counts. " +
"Use list_pulls first to find the PR number.")]
public async Task<object> read_pull(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Pull request number (integer).")] int number,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
// 并行拉取 PR 主体、评论、变更文件
var pullTask = gitea.GetPullAsync(owner, repo, number, ct);
var commentsTask = gitea.GetPullCommentsAsync(owner, repo, number, ct);
var filesTask = gitea.GetPullFilesAsync(owner, repo, number, ct);
await Task.WhenAll(pullTask, commentsTask, filesTask);
var pull = await pullTask;
var comments = await commentsTask;
var files = await filesTask;
return new
{
number = pull.Number,
title = pull.Title,
body = pull.Body,
state = pull.State,
html_url = pull.HtmlUrl,
author = pull.User?.Login,
head = pull.Head?.Ref,
head_sha = pull.Head?.Sha,
base_branch = pull.Base?.Ref,
merged = pull.Merged,
mergeable = pull.Mergeable,
labels = pull.Labels?.Select(l => l.Name).ToList() ?? [],
created_at = pull.CreatedAt,
updated_at = pull.UpdatedAt,
closed_at = pull.ClosedAt,
merged_at = pull.MergedAt,
comments = comments.Select(c => new
{
id = c.Id,
author = c.User?.Login,
body = c.Body,
created_at = c.CreatedAt,
}).ToList(),
changed_files = files.Select(f => new
{
filename = f.Filename,
status = f.Status,
additions = f.Additions,
deletions = f.Deletions,
changes = f.Changes,
}).ToList(),
};
}
}
+89
View File
@@ -0,0 +1,89 @@
using GiteaMcp.Config;
using GiteaMcp.Services;
using GiteaMcp.Services.Models;
using Microsoft.Extensions.Options;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>仓库级别 Toollist_repos / read_repo</summary>
[McpServerToolType]
public class RepoTools(
GiteaApiClient gitea,
GiteaRepoFilter filter,
IOptions<GiteaOptions> opts)
{
private readonly GiteaOptions _opts = opts.Value;
[McpServerTool]
[Description(
"List Gitea repositories accessible to the admin token. " +
"When owner is omitted, returns ALL repos across personal account and all orgs (up to limit). " +
"Use visibility='private' to show only private repos, 'public' for public-only. " +
"Returns: owner, repo name, description, default_branch, private flag, size (KB), updated_at, html_url. " +
"Tip: call this first to discover available repos before using read_repo or read_file.")]
public async Task<List<object>> list_repos(
[Description("Filter by owner login (user or org name). Omit to list everything.")] string? owner = null,
[Description("Visibility filter: 'public', 'private', or 'all' (default 'all').")] string? visibility = null,
[Description("Max number of repos to return. Default 50, max 50.")] int? limit = null,
CancellationToken ct = default)
{
var vis = visibility ?? "all";
var lim = Math.Min(limit ?? _opts.DefaultLimit, 50);
var repos = await gitea.SearchReposAsync(owner, vis, lim, ct);
repos = filter.Filter(repos);
return repos.Select(r => (object)new
{
owner = r.Owner?.Login ?? r.FullName.Split('/').FirstOrDefault() ?? "",
repo = r.Name,
full_name = r.FullName,
description = r.Description,
default_branch = r.DefaultBranch,
@private = r.Private,
mirror = r.Mirror,
archived = r.Archived,
size_kb = r.Size,
updated_at = r.UpdatedAt,
html_url = r.HtmlUrl,
}).ToList();
}
[McpServerTool]
[Description(
"Get detailed metadata for a single Gitea repository: topics, homepage, default branch, " +
"stars, forks, archived status, mirror flag, size, and description. " +
"Use this after list_repos to inspect a specific repo before reading files or commits.")]
public async Task<object> read_repo(
[Description("Repository owner (user login or org name).")] string owner,
[Description("Repository name (without owner prefix).")] string repo,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
var r = await gitea.GetRepoAsync(owner, repo, ct);
return new
{
owner = r.Owner?.Login ?? owner,
repo = r.Name,
full_name = r.FullName,
description = r.Description,
default_branch = r.DefaultBranch,
@private = r.Private,
fork = r.Fork,
mirror = r.Mirror,
archived = r.Archived,
stars = r.StarsCount,
forks = r.ForksCount,
size_kb = r.Size,
website = r.Website,
topics = r.Topics ?? [],
html_url = r.HtmlUrl,
clone_url = r.CloneUrl,
updated_at = r.UpdatedAt,
};
}
}
+75
View File
@@ -0,0 +1,75 @@
using GiteaMcp.Services;
using GiteaMcp.Services.Models;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>代码搜索 Toolsearch_code</summary>
[McpServerToolType]
public class SearchTools(
GiteaApiClient gitea,
GiteaRepoFilter filter)
{
[McpServerTool]
[Description(
"Search code across Gitea repositories using Gitea's built-in code indexer. " +
"Requires Gitea to have REPO_INDEXER_ENABLED=true in app.ini. " +
"If the indexer is not enabled, returns an explanatory error instead of silently returning empty. " +
"Scope: when owner+repo are provided, searches only that repo; otherwise searches all accessible repos. " +
"Returns: owner, repo, file path, line number, and a preview snippet of the matching line. " +
"Limit: max 50 results. For large codebases, narrow with owner or repo.")]
public async Task<object> search_code(
[Description("Search query string. Supports keywords; no regex.")] string query,
[Description("Restrict search to this owner (user login or org name). Optional.")] string? owner = null,
[Description("Restrict search to this repo name (requires owner). Optional.")] string? repo = null,
[Description("Max number of results. Default 50.")] int? limit = null,
CancellationToken ct = default)
{
var lim = Math.Min(limit ?? 50, 50);
// 检查是否需要过滤黑名单
if (!string.IsNullOrWhiteSpace(owner) && !string.IsNullOrWhiteSpace(repo)
&& filter.IsBlocked($"{owner}/{repo}"))
{
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
}
// 调 Gitea code search 端点(仅在 [indexer] REPO_INDEXER_ENABLED=true 时可用)。
// indexer 未启用 → API 返回 404GiteaApiClient.EnsureSuccessAsync 抛 KeyNotFoundException
// 这里捕获后返回结构化降级提示,避免 swallow 到空数组让 Claude 误以为"搜不到"。
try
{
var codeResult = await gitea.SearchCodeAsync(query, owner, repo, lim, ct);
var hits = codeResult.Data
.Where(d => d.Repo == null || !filter.IsBlocked(d.Repo.FullName))
.Take(lim)
.Select(d => (object)new
{
owner = d.Repo?.Owner?.Login ?? "",
repo = d.Repo?.Name ?? "",
path = d.Filename,
// Gitea code search 不返回精确行号,前端可在 preview 里自行定位
line = 0,
preview = d.Content?.Length > 200 ? d.Content[..200] + "..." : d.Content ?? "",
})
.ToList();
return new { ok = true, results = hits };
}
catch (KeyNotFoundException)
{
// indexer 未启用 → 404;返回结构化提示,不要 swallow 成空 results
return new
{
ok = false,
error = "indexer_disabled",
notice = "Gitea code search endpoint returned 404. " +
"Enable the code indexer by setting [indexer] REPO_INDEXER_ENABLED=true in app.ini and restart Gitea. " +
"Workaround: use list_tree + read_file to navigate files manually.",
results = Array.Empty<object>(),
};
}
}
}
+104
View File
@@ -0,0 +1,104 @@
using GiteaMcp.Config;
using GiteaMcp.Services;
using GiteaMcp.Services.Models;
using Microsoft.Extensions.Options;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace GiteaMcp.Tools;
/// <summary>文件树与文件内容 Toollist_tree / read_file</summary>
[McpServerToolType]
public class TreeTools(
GiteaApiClient gitea,
GiteaRepoFilter filter,
IOptions<GiteaOptions> opts)
{
private readonly GiteaOptions _opts = opts.Value;
[McpServerTool]
[Description(
"List the file tree of a Gitea repository at a given ref (branch/tag/SHA). " +
"When recursive=false (default), returns only top-level entries. " +
"When recursive=true, returns all files up to max_entries=500 — use this to map repo structure. " +
"Returns: path, type ('blob'=file, 'tree'=directory), size (bytes), sha. " +
"For very large repos (>500 files), truncated=true will be set; narrow down by adjusting paths manually.")]
public async Task<object> list_tree(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("Branch name, tag, or commit SHA. Defaults to the repo's default branch.")] string? @ref = null,
[Description("Recursively include all files in subdirectories. Default false.")] bool recursive = false,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
// ref 未提供时,先拿 default_branch
if (string.IsNullOrWhiteSpace(@ref))
{
var repoMeta = await gitea.GetRepoAsync(owner, repo, ct);
@ref = repoMeta.DefaultBranch;
}
var tree = await gitea.GetTreeAsync(owner, repo, @ref, recursive, ct);
const int MaxEntries = 500;
var entries = tree.Tree;
bool truncated = tree.Truncated || entries.Count > MaxEntries;
if (entries.Count > MaxEntries)
entries = entries.Take(MaxEntries).ToList();
return new
{
owner,
repo,
@ref,
truncated,
entry_count = entries.Count,
entries = entries.Select(e => new
{
path = e.Path,
type = e.Type,
size = e.Size,
sha = e.Sha,
}),
};
}
[McpServerTool]
[Description(
"Read the raw text content of a file from a Gitea repository. " +
"Returns the file as UTF-8 text. Binary files will appear garbled — check file extension first. " +
"Truncated to max_bytes (default 1MB); when truncated=true, the content is cut off. " +
"Use list_tree first to discover file paths.")]
public async Task<object> read_file(
[Description("Repository owner.")] string owner,
[Description("Repository name.")] string repo,
[Description("File path relative to repo root, e.g. 'src/Main.cs' or 'README.md'.")] string path,
[Description("Branch, tag, or SHA. Defaults to repo's default branch.")] string? @ref = null,
[Description("Max bytes to read. Default 1048576 (1MB). Reduce for large binary-adjacent files.")] int? max_bytes = null,
CancellationToken ct = default)
{
if (filter.IsBlocked($"{owner}/{repo}"))
throw new UnauthorizedAccessException($"Repo {owner}/{repo} is on the access blocklist.");
if (string.IsNullOrWhiteSpace(@ref))
{
var repoMeta = await gitea.GetRepoAsync(owner, repo, ct);
@ref = repoMeta.DefaultBranch;
}
var maxB = Math.Min(max_bytes ?? _opts.MaxFileBytes, _opts.MaxFileBytes);
var (content, truncated) = await gitea.GetRawFileAsync(owner, repo, @ref, path, maxB, ct);
return new
{
owner,
repo,
@ref,
path,
truncated,
content,
};
}
}