f929c58c6b
* Add CSV output for list tools under insiders mode * fix: resolve rebase feature flag conflicts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Simplify feature-flag handling: collapse CSV dual-variant + skip filtering when no checker (#2516) * refactor: generic toolset+name sort, clarify feature flag intent Address review feedback on #2450: - Collapse the three near-identical sort helpers in pkg/inventory/filters.go into a generic sortByToolsetThenName so adding new inventory item types doesn't require copying the comparator. - Expand the doc comments on the three *WithoutFeatureFiltering helpers to spell out why they exist: HTTP mode builds a static (process-wide) inventory as an upper bound, but per-request feature flags from headers (X-MCP-Features, X-MCP-Insiders) are evaluated later, so feature-flagged variants must be preserved here. - Strengthen the doc comment on ResolveFeatureFlags to make the contract explicit: user-supplied flags are validated against AllowedFeatureFlags, but insiders expansion deliberately is not — InsidersFeatureFlags may include server-controlled flags that are not user-toggleable. CORS comments are intentionally left for the PR author. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * docs(feature-flags): clarify allowed and insiders sets are independent Also add tests covering: - a user-toggleable flag (FeatureFlagIssuesGranular) that insiders does not turn on automatically - insiders mode not turning on user-only allowed flags Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor(inventory): collapse three *WithoutFeatureFiltering helpers into StaticUpperBound The three parallel methods (AvailableToolsWithoutFeatureFiltering, AvailableResourceTemplatesWithoutFeatureFiltering, AvailablePromptsWithoutFeatureFiltering) were always called as a triple in exactly two places: HTTP buildStaticInventory and its test mirror. They exist because the dual-variant pattern (sibling tools with mirrored FeatureFlagEnable / FeatureFlagDisable on the same name, e.g. CSV output) makes feature filtering at static-build time impossible — both variants must be kept and resolved per-request. Replace the three with one method, Inventory.StaticUpperBound(ctx), that returns (tools, resources, prompts) and carries the rationale in its doc comment. Reduces API surface, eliminates the triplication, and makes the single "skip feature filtering" concept obvious to readers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor: simplify feature-flag handling Two related simplifications, both about treating insiders as a meta flag that expands once at startup and then stops mattering: - Collapse CSV's dual-variant pattern into a single tool whose handler performs a runtime feature-flag check via deps.IsFeatureEnabled. CSV is a pure response-format toggle, not a schema change, so it does not need the dual-name pattern that genuine schema variants (granular issues/PRs) still use. - When no feature checker is installed, skip feature-flag filtering and return the full upper bound. The static HTTP inventory now uses plain AvailableTools/Resources/Prompts; the per-request inventory always installs a checker, so MCP registration (which serves a tool name once) always sees a deduplicated set. The bespoke StaticUpperBound helper and the isToolEnabledWithFeatureFlags split go away. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * ci(mcp-diff): add insiders + per-feature configs The mcp-diff matrix now includes: - --insiders (and --insiders --read-only) - one config per github.AllowedFeatureFlags entry, generated by script/print-mcp-diff-configs so new user-controllable flags get diffed automatically without editing the workflow Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * docs(insiders): explain feature-flag resolution for contributors Adds a 'How feature flags are resolved' section covering: - Insiders is a meta flag, like 'all'/'default' for toolsets - User input -> allowlist filter -> insiders expansion -> server-side fallback (remote only) - AllowedFeatureFlags vs InsidersFeatureFlags are independent - How to add a new feature flag, including the TestGitHubPackageDoesNotReadInsidersMode guard Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor(inventory): make feature-flag gating a regular ToolFilter Move tool feature-flag evaluation out of isToolEnabled and into a ToolFilter installed at the head of the pipeline by Build() when WithFeatureChecker received a non-nil checker. The 'no checker = no filtering' contract is now expressed structurally (the filter isn't installed) instead of by a runtime nil check inside the helper. Resources and prompts have no filter pipeline, so they call the now-pure featureFlagAllowed helper behind an explicit r.featureChecker != nil guard at the iteration site. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * perf(inventory): cache extracted toolset IDs in sort comparator Avoid evaluating the extractor closures up to three times per comparison. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: correct MCP features header in cors * docs: regenerate README for CSV output toolset Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: remove duplicate MCPFeaturesHeader from CORS headers * ci(mcp-diff): add streamable-http job with header-based configs Adds a sibling mcp-diff-http job that exercises the streamable-http transport against a shared HTTP server, with per-config settings supplied via X-MCP-* request headers — mirroring how the remote server is invoked in production (server-side defaults + per-user header overrides). The config generator gains a -transport flag: - stdio (default, unchanged behaviour) - http-headers (emits headers-only configs targeting a shared server) Two new combined entries layer multiple headers together as a smoke test for header-merging regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * docs: regenerate after merging main Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Sam Morrow <info@sam-morrow.com> Co-authored-by: sammorrowdrums <sammorrowdrums@github.com>
186 lines
6.2 KiB
Go
186 lines
6.2 KiB
Go
package github
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"strings"
|
|
"time"
|
|
|
|
gherrors "github.com/github/github-mcp-server/pkg/errors"
|
|
"github.com/github/github-mcp-server/pkg/inventory"
|
|
"github.com/github/github-mcp-server/pkg/octicons"
|
|
"github.com/github/github-mcp-server/pkg/translations"
|
|
"github.com/github/github-mcp-server/pkg/utils"
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
)
|
|
|
|
type MCPServerConfig struct {
|
|
// Version of the server
|
|
Version string
|
|
|
|
// GitHub Host to target for API requests (e.g. github.com or github.enterprise.com)
|
|
Host string
|
|
|
|
// GitHub Token to authenticate with the GitHub API
|
|
Token string
|
|
|
|
// EnabledToolsets is a list of toolsets to enable
|
|
// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#tool-configuration
|
|
EnabledToolsets []string
|
|
|
|
// EnabledTools is a list of specific tools to enable (additive to toolsets)
|
|
// When specified, these tools are registered in addition to any specified toolset tools
|
|
EnabledTools []string
|
|
|
|
// EnabledFeatures is a list of feature flags that are enabled
|
|
// Items with FeatureFlagEnable matching an entry in this list will be available
|
|
EnabledFeatures []string
|
|
|
|
// ReadOnly indicates if we should only offer read-only tools
|
|
ReadOnly bool
|
|
|
|
// Translator provides translated text for the server tooling
|
|
Translator translations.TranslationHelperFunc
|
|
|
|
// Content window size
|
|
ContentWindowSize int
|
|
|
|
// LockdownMode indicates if we should enable lockdown mode
|
|
LockdownMode bool
|
|
|
|
// InsidersMode expands to the curated set of feature flags enabled for insiders.
|
|
InsidersMode bool
|
|
|
|
// Logger is used for logging within the server
|
|
Logger *slog.Logger
|
|
// RepoAccessTTL overrides the default TTL for repository access cache entries.
|
|
RepoAccessTTL *time.Duration
|
|
|
|
// ExcludeTools is a list of tool names that should be disabled regardless of
|
|
// other configuration. These tools will be excluded even if their toolset is enabled
|
|
// or they are explicitly listed in EnabledTools.
|
|
ExcludeTools []string
|
|
|
|
// TokenScopes contains the OAuth scopes available to the token.
|
|
// When non-nil, tools requiring scopes not in this list will be hidden.
|
|
// This is used for PAT scope filtering where we can't issue scope challenges.
|
|
TokenScopes []string
|
|
|
|
// Additional server options to apply
|
|
ServerOptions []MCPServerOption
|
|
}
|
|
|
|
type MCPServerOption func(*mcp.ServerOptions)
|
|
|
|
func NewMCPServer(ctx context.Context, cfg *MCPServerConfig, deps ToolDependencies, inv *inventory.Inventory, middleware ...mcp.Middleware) (*mcp.Server, error) {
|
|
// Create the MCP server
|
|
serverOpts := &mcp.ServerOptions{
|
|
Instructions: inv.Instructions(),
|
|
Logger: cfg.Logger,
|
|
CompletionHandler: CompletionsHandler(deps.GetClient),
|
|
}
|
|
|
|
// Apply any additional server options
|
|
for _, o := range cfg.ServerOptions {
|
|
o(serverOpts)
|
|
}
|
|
|
|
ghServer := NewServer(cfg.Version, cfg.Translator("SERVER_NAME", "github-mcp-server"), cfg.Translator("SERVER_TITLE", "GitHub MCP Server"), serverOpts)
|
|
|
|
// Add middlewares. Order matters - for example, the error context middleware should be applied last so that it runs FIRST (closest to the handler) to ensure all errors are captured,
|
|
// and any middleware that needs to read or modify the context should be before it.
|
|
ghServer.AddReceivingMiddleware(middleware...)
|
|
ghServer.AddReceivingMiddleware(InjectDepsMiddleware(deps))
|
|
ghServer.AddReceivingMiddleware(addGitHubAPIErrorToContext)
|
|
|
|
if unrecognized := inv.UnrecognizedToolsets(); len(unrecognized) > 0 {
|
|
cfg.Logger.Warn("Warning: unrecognized toolsets ignored", "toolsets", strings.Join(unrecognized, ", "))
|
|
}
|
|
|
|
// Register GitHub tools/resources/prompts from the inventory.
|
|
inv.RegisterAll(ctx, ghServer, deps)
|
|
|
|
return ghServer, nil
|
|
}
|
|
|
|
// ResolvedEnabledToolsets determines which toolsets should be enabled based on config.
|
|
// Returns nil for "use defaults", empty slice for "none", or explicit list.
|
|
func ResolvedEnabledToolsets(enabledToolsets []string, enabledTools []string) []string {
|
|
if enabledToolsets != nil {
|
|
return enabledToolsets
|
|
}
|
|
if len(enabledTools) > 0 {
|
|
// When specific tools are requested but no toolsets, don't use default toolsets
|
|
// This matches the original behavior: --tools=X alone registers only X
|
|
return []string{}
|
|
}
|
|
|
|
// nil means "use defaults" in WithToolsets
|
|
return nil
|
|
}
|
|
|
|
func addGitHubAPIErrorToContext(next mcp.MethodHandler) mcp.MethodHandler {
|
|
return func(ctx context.Context, method string, req mcp.Request) (result mcp.Result, err error) {
|
|
// Ensure the context is cleared of any previous errors
|
|
// as context isn't propagated through middleware
|
|
ctx = gherrors.ContextWithGitHubErrors(ctx)
|
|
return next(ctx, method, req)
|
|
}
|
|
}
|
|
|
|
// NewServer creates a new GitHub MCP server with the given version, server
|
|
// name, display title, and options. If name or title are empty the defaults
|
|
// "github-mcp-server" and "GitHub MCP Server" are used.
|
|
func NewServer(version, name, title string, opts *mcp.ServerOptions) *mcp.Server {
|
|
if opts == nil {
|
|
opts = &mcp.ServerOptions{}
|
|
}
|
|
|
|
if name == "" {
|
|
name = "github-mcp-server"
|
|
}
|
|
if title == "" {
|
|
title = "GitHub MCP Server"
|
|
}
|
|
|
|
// Create a new MCP server
|
|
s := mcp.NewServer(&mcp.Implementation{
|
|
Name: name,
|
|
Title: title,
|
|
Version: version,
|
|
Icons: octicons.Icons("mark-github"),
|
|
}, opts)
|
|
|
|
return s
|
|
}
|
|
|
|
func CompletionsHandler(getClient GetClientFn) func(ctx context.Context, req *mcp.CompleteRequest) (*mcp.CompleteResult, error) {
|
|
return func(ctx context.Context, req *mcp.CompleteRequest) (*mcp.CompleteResult, error) {
|
|
if req == nil || req.Params == nil || req.Params.Ref == nil {
|
|
return nil, fmt.Errorf("missing required parameter: ref")
|
|
}
|
|
switch req.Params.Ref.Type {
|
|
case "ref/resource":
|
|
if strings.HasPrefix(req.Params.Ref.URI, "repo://") {
|
|
return RepositoryResourceCompletionHandler(getClient)(ctx, req)
|
|
}
|
|
return nil, fmt.Errorf("unsupported resource URI: %s", req.Params.Ref.URI)
|
|
case "ref/prompt":
|
|
return nil, nil
|
|
default:
|
|
return nil, fmt.Errorf("unsupported ref type: %s", req.Params.Ref.Type)
|
|
}
|
|
}
|
|
}
|
|
|
|
func MarshalledTextResult(v any) *mcp.CallToolResult {
|
|
data, err := json.Marshal(v)
|
|
if err != nil {
|
|
return utils.NewToolResultErrorFromErr("failed to marshal text result to json", err)
|
|
}
|
|
|
|
return utils.NewToolResultText(string(data))
|
|
}
|