Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/streamable-http.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
124 changes: 124 additions & 0 deletions pkg/github/graphql_operation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
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 ToolsetMetadataGraphQL = inventory.ToolsetMetadata{
ID: "graphql",
Description: "Execute operations against the GitHub GraphQL API",
Icon: "code-square",
}

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,
}
}

// 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(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, *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
}
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 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
}
cleanGraphQLValue(response.Data)
for _, entry := range response.Errors {
cleanGraphQLValue(entry)
}
result := MarshalledTextResult(response)
result.IsError = len(response.Errors) > 0
return result, &response, nil
})
}
37 changes: 37 additions & 0 deletions pkg/github/graphql_operation_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
9 changes: 7 additions & 2 deletions pkg/github/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package github

import (
"context"
"os"
"slices"
"strings"

Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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, GraphQLQuery(), GraphQLMutation())
}
return withCSVOutput(tools)
}

// ToBoolPtr converts a bool to a *bool pointer.
Expand Down
4 changes: 3 additions & 1 deletion pkg/skills/catalog/availability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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
Expand Down