From 50994296db1c313149d50631491aae95fab871b8 Mon Sep 17 00:00:00 2001 From: Gwom Date: Tue, 17 Nov 2026 22:39:00 +0000 Subject: [PATCH 1/2] Add operator-enabled direct GraphQL query and mutation tools --- docs/streamable-http.md | 8 +++ pkg/github/graphql_operation.go | 86 ++++++++++++++++++++++++++++ pkg/github/graphql_operation_test.go | 37 ++++++++++++ pkg/github/tools.go | 9 ++- 4 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 pkg/github/graphql_operation.go create mode 100644 pkg/github/graphql_operation_test.go diff --git a/docs/streamable-http.md b/docs/streamable-http.md index e0fb461ef2..fe61f9c769 100644 --- a/docs/streamable-http.md +++ b/docs/streamable-http.md @@ -191,3 +191,11 @@ To provide PAT credentials, or to customize server behavior preferences, you can ``` See [Remote Server](./remote-server.md) documentation for more details on client configuration options. + +## Direct GraphQL operations (opt-in) + +Set `GITHUB_MCP_ENABLE_GRAPHQL=true` on the server and select the `graphql` toolset, for example with `--toolsets default,graphql`. Restart the server and refresh the client's tool list. Without the environment variable the tools are unavailable, including through the `all` toolset. + +The read tool, `github_graphql_query`, and the write tool, `github_graphql_mutation`, use the current request's GitHub credentials. Enabling direct GraphQL gives callers access to the operations those credentials permit, including operations without a dedicated MCP tool. Operators relying on a narrow allowlist of named actions should leave the toolset disabled. Read-only mode filters out the mutation tool. Both tools refuse execution when lockdown mode or IFC labels are active. + +For example, call `github_graphql_query` with `{"operation":"{ viewer { login } }"}`. To pass variables, supply the variable definitions followed by the selection set in `operation`, and the values in `variables`. The server supplies the operation kind and name. GitHub's response can include partial data and errors together. diff --git a/pkg/github/graphql_operation.go b/pkg/github/graphql_operation.go new file mode 100644 index 0000000000..b4082bcb1f --- /dev/null +++ b/pkg/github/graphql_operation.go @@ -0,0 +1,86 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "strings" + + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +var graphqlToolset = inventory.ToolsetMetadata{ + ID: "graphql", + Description: "Execute operations against the GitHub GraphQL API", + Icon: "code", +} + +type graphqlOperationInput struct { + Operation string `json:"operation" jsonschema:"Operation body starting with optional variable definitions then the selection set. Omit the query or mutation keyword and operation name. Fragment definitions may follow."` + Variables map[string]any `json:"variables,omitempty" jsonschema:"Values for the operation variables."` +} + +type graphqlOperationPayload struct { + Query string `json:"query"` + OperationName string `json:"operationName"` + Variables map[string]any `json:"variables,omitempty"` +} + +// Set both the operation type and the selected name on the server. Even a +// document containing other operations can only execute the named operation. +func graphqlPayload(input graphqlOperationInput, write bool) graphqlOperationPayload { + kind := "query" + if write { + kind = "mutation" + } + return graphqlOperationPayload{ + Query: kind + " MCPRequest " + input.Operation, + OperationName: "MCPRequest", + Variables: input.Variables, + } +} + +func graphqlOperationTool(write bool) inventory.ServerTool { + name, description := "github_graphql_query", "Read GitHub data with a GraphQL query using the current GitHub credential." + if write { + name, description = "github_graphql_mutation", "Change GitHub data with a GraphQL mutation using the current GitHub credential." + } + return NewTool(graphqlToolset, mcp.Tool{ + Name: name, + Description: description, + InputSchema: contextToolInputSchema[graphqlOperationInput](nil), + Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !write, DestructiveHint: ToBoolPtr(write)}, + }, scopes.NoScopes(), func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input graphqlOperationInput) (*mcp.CallToolResult, any, error) { + if deps.GetFlags(ctx).LockdownMode || deps.IsFeatureEnabled(ctx, FeatureFlagIFCLabels) { + return utils.NewToolResultError("Direct GraphQL is unavailable with lockdown or IFC labels enabled"), nil, nil + } + if strings.TrimSpace(input.Operation) == "" { + return utils.NewToolResultError("A GraphQL operation body is required"), nil, nil + } + client, err := deps.GetClient(ctx) + if err != nil { + return utils.NewToolResultErrorFromErr("Get GitHub client", err), nil, nil + } + endpoint := "graphql" + if strings.HasSuffix(client.BaseURL(), "/api/v3/") { + endpoint = "/api/graphql" + } + req, err := client.NewRequest(ctx, http.MethodPost, endpoint, graphqlPayload(input, write)) + if err != nil { + return utils.NewToolResultErrorFromErr("Build GitHub GraphQL request", err), nil, nil + } + var response struct { + Data json.RawMessage `json:"data,omitempty"` + Errors []json.RawMessage `json:"errors,omitempty"` + } + if _, err := client.Do(req, &response); err != nil { + return utils.NewToolResultErrorFromErr("GitHub GraphQL request failed", err), nil, nil + } + result := MarshalledTextResult(response) + result.IsError = len(response.Errors) > 0 + return result, nil, nil + }) +} diff --git a/pkg/github/graphql_operation_test.go b/pkg/github/graphql_operation_test.go new file mode 100644 index 0000000000..db68dd7f97 --- /dev/null +++ b/pkg/github/graphql_operation_test.go @@ -0,0 +1,37 @@ +package github + +import ( + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/require" +) + +func TestGraphQLOperationSelection(t *testing.T) { + body := "($id: ID!) { node(id: $id) { id } }" + variables := map[string]any{"id": "example"} + in := graphqlOperationInput{Operation: body, Variables: variables} + read := graphqlPayload(in, false) + require.Equal(t, "query MCPRequest "+body, read.Query) + require.Equal(t, "MCPRequest", read.OperationName) + require.Equal(t, variables, read.Variables) + write := graphqlPayload(in, true) + require.Equal(t, "mutation MCPRequest "+body, write.Query) + require.Equal(t, read.OperationName, write.OperationName) + + // Only the server-selected read operation can run, even if the caller + // includes an additional, differently named mutation in the document. + in.Operation = "{ viewer { login } } mutation Other { __typename }" + read = graphqlPayload(in, false) + require.Equal(t, "MCPRequest", read.OperationName) + require.Equal(t, "query MCPRequest "+in.Operation, read.Query) +} + +func TestGraphQLOperationRegistration(t *testing.T) { + server := mcp.NewServer(&mcp.Implementation{Name: "discovery-test", Version: "1"}, nil) + for _, write := range []bool{false, true} { + tool := graphqlOperationTool(write) + require.NotNil(t, tool.Tool.InputSchema) + tool.RegisterFunc(server, nil) + } +} diff --git a/pkg/github/tools.go b/pkg/github/tools.go index c8399d4728..dce64e0b63 100644 --- a/pkg/github/tools.go +++ b/pkg/github/tools.go @@ -2,6 +2,7 @@ package github import ( "context" + "os" "slices" "strings" @@ -222,7 +223,7 @@ func newToolConfig(opts []ToolOption) toolConfig { // AllTools returns all tools with their embedded toolset metadata. // Tool functions return ServerTool directly with toolset info. func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []inventory.ServerTool { - return withCSVOutput([]inventory.ServerTool{ + tools := []inventory.ServerTool{ // Context tools GetMe(t), GetTeams(t), @@ -415,7 +416,11 @@ func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []invent GranularUnhidePullRequestReviewComment(t), GranularHidePullRequestReview(t), GranularUnhidePullRequestReview(t), - }) + } + if os.Getenv("GITHUB_MCP_ENABLE_GRAPHQL") == "true" { + tools = append(tools, graphqlOperationTool(false), graphqlOperationTool(true)) + } + return withCSVOutput(tools) } // ToBoolPtr converts a bool to a *bool pointer. From 0abff7d691f8ba54c1a850c638fbb04500d4e58f Mon Sep 17 00:00:00 2001 From: Gwom Date: Wed, 18 Nov 2026 09:51:56 +0000 Subject: [PATCH 2/2] Integrate GraphQL with typed responses, sanitisation and catalog checks --- pkg/github/graphql_operation.go | 58 ++++++++++++++++++++----- pkg/github/tools.go | 2 +- pkg/skills/catalog/availability_test.go | 4 +- 3 files changed, 52 insertions(+), 12 deletions(-) diff --git a/pkg/github/graphql_operation.go b/pkg/github/graphql_operation.go index b4082bcb1f..0b4003c737 100644 --- a/pkg/github/graphql_operation.go +++ b/pkg/github/graphql_operation.go @@ -1,21 +1,24 @@ package github import ( + "bytes" "context" "encoding/json" "net/http" "strings" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/sanitize" "github.com/github/github-mcp-server/v2/pkg/scopes" "github.com/github/github-mcp-server/v2/pkg/utils" "github.com/modelcontextprotocol/go-sdk/mcp" ) -var graphqlToolset = inventory.ToolsetMetadata{ +var ToolsetMetadataGraphQL = inventory.ToolsetMetadata{ ID: "graphql", Description: "Execute operations against the GitHub GraphQL API", - Icon: "code", + Icon: "code-square", } type graphqlOperationInput struct { @@ -43,17 +46,44 @@ func graphqlPayload(input graphqlOperationInput, write bool) graphqlOperationPay } } +// GraphQLQuery constructs the direct read tool. +func GraphQLQuery() inventory.ServerTool { return graphqlOperationTool(false) } + +// GraphQLMutation constructs the direct write tool. +func GraphQLMutation() inventory.ServerTool { return graphqlOperationTool(true) } + +type graphQLResponse struct { + Data map[string]any `json:"data"` + Errors []map[string]any `json:"errors,omitempty"` +} + +func cleanGraphQLValue(value any) any { + switch v := value.(type) { + case string: + return sanitize.Content(v) + case []any: + for i := range v { + v[i] = cleanGraphQLValue(v[i]) + } + case map[string]any: + for key, child := range v { + v[key] = cleanGraphQLValue(child) + } + } + return value +} + func graphqlOperationTool(write bool) inventory.ServerTool { name, description := "github_graphql_query", "Read GitHub data with a GraphQL query using the current GitHub credential." if write { name, description = "github_graphql_mutation", "Change GitHub data with a GraphQL mutation using the current GitHub credential." } - return NewTool(graphqlToolset, mcp.Tool{ + return NewTool(ToolsetMetadataGraphQL, mcp.Tool{ Name: name, Description: description, InputSchema: contextToolInputSchema[graphqlOperationInput](nil), Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !write, DestructiveHint: ToBoolPtr(write)}, - }, scopes.NoScopes(), func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input graphqlOperationInput) (*mcp.CallToolResult, any, error) { + }, scopes.NoScopes(), func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input graphqlOperationInput) (*mcp.CallToolResult, *graphQLResponse, error) { if deps.GetFlags(ctx).LockdownMode || deps.IsFeatureEnabled(ctx, FeatureFlagIFCLabels) { return utils.NewToolResultError("Direct GraphQL is unavailable with lockdown or IFC labels enabled"), nil, nil } @@ -72,15 +102,23 @@ func graphqlOperationTool(write bool) inventory.ServerTool { if err != nil { return utils.NewToolResultErrorFromErr("Build GitHub GraphQL request", err), nil, nil } - var response struct { - Data json.RawMessage `json:"data,omitempty"` - Errors []json.RawMessage `json:"errors,omitempty"` + var raw json.RawMessage + resp, err := client.Do(req, &raw) + if err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, "GitHub GraphQL request failed", resp, err), nil, nil + } + var response graphQLResponse + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + if err := decoder.Decode(&response); err != nil { + return utils.NewToolResultErrorFromErr("Decode GraphQL response", err), nil, nil } - if _, err := client.Do(req, &response); err != nil { - return utils.NewToolResultErrorFromErr("GitHub GraphQL request failed", err), nil, nil + cleanGraphQLValue(response.Data) + for _, entry := range response.Errors { + cleanGraphQLValue(entry) } result := MarshalledTextResult(response) result.IsError = len(response.Errors) > 0 - return result, nil, nil + return result, &response, nil }) } diff --git a/pkg/github/tools.go b/pkg/github/tools.go index dce64e0b63..67b824efa5 100644 --- a/pkg/github/tools.go +++ b/pkg/github/tools.go @@ -418,7 +418,7 @@ func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []invent GranularUnhidePullRequestReview(t), } if os.Getenv("GITHUB_MCP_ENABLE_GRAPHQL") == "true" { - tools = append(tools, graphqlOperationTool(false), graphqlOperationTool(true)) + tools = append(tools, GraphQLQuery(), GraphQLMutation()) } return withCSVOutput(tools) } diff --git a/pkg/skills/catalog/availability_test.go b/pkg/skills/catalog/availability_test.go index 4e60f3561d..38f9b863ec 100644 --- a/pkg/skills/catalog/availability_test.go +++ b/pkg/skills/catalog/availability_test.go @@ -23,6 +23,8 @@ var toolCoverageExemptions = map[string]string{ "create_repository_ruleset": "Repository governance configuration is a distinct workflow not covered by the current catalog.", "custom_properties_read": "Custom-property administration is a distinct governance workflow not covered by the current catalog.", "custom_properties_write": "Custom-property administration is a distinct governance workflow not covered by the current catalog.", + "github_graphql_query": "Direct schema queries are operator-enabled and independent of bundled workflows.", + "github_graphql_mutation": "Direct schema mutations are operator-enabled and independent of bundled workflows.", "get_gist": "Gist lifecycle is separate from the repository workflows covered by the current catalog.", "hide_issue_comment": "Comment moderation is outside the current issue authoring and backlog workflows.", "hide_pull_request_review": "Review moderation is outside the current pull-request authoring and review workflows.", @@ -58,7 +60,7 @@ var toolCoverageExemptions = map[string]string{ } func TestCatalogToolRequirementsAreRegistered(t *testing.T) { - t.Parallel() + t.Setenv("GITHUB_MCP_ENABLE_GRAPHQL", "true") known := make(map[string]bool) for _, tool := range github.AllTools(translations.NullTranslationHelper) { known[tool.Tool.Name] = true