-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Graphql toolset #645
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
akenneth
wants to merge
4
commits into
github:main
Choose a base branch
from
akenneth:graphql-tools-feature
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Graphql toolset #645
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# GraphQL Tools | ||
|
||
This document describes the GraphQL tools added to the GitHub MCP server that provide direct access to GitHub's GraphQL API. | ||
|
||
## Tools | ||
|
||
### execute_graphql_query | ||
|
||
Executes a GraphQL query against GitHub's API and returns the results. | ||
|
||
#### Parameters | ||
|
||
- `query` (required): The GraphQL query string to execute | ||
- `variables` (optional): Variables for the GraphQL query as a JSON object | ||
|
||
#### Response | ||
|
||
Returns a JSON object with: | ||
|
||
- `query`: The original query string | ||
- `variables`: The variables passed to the query | ||
- `success`: Boolean indicating if the query executed successfully | ||
- `data`: The GraphQL response data (if successful) | ||
- `error`: Error message if execution failed | ||
- `error_type`: Type of execution error (rate_limit, authentication, permission, not_found, execution_error) | ||
- `graphql_errors`: Any GraphQL-specific errors from the response | ||
|
||
#### Example | ||
|
||
```json | ||
{ | ||
"query": "query { viewer { login } }", | ||
"variables": {}, | ||
"success": true, | ||
"data": { | ||
"viewer": { | ||
"login": "username" | ||
} | ||
} | ||
} | ||
``` | ||
|
||
## Implementation Details | ||
|
||
### Execution | ||
|
||
The execution tool uses GitHub's REST client to make raw HTTP requests to the GraphQL endpoint (`/graphql`), allowing for arbitrary GraphQL query execution while maintaining proper authentication and error handling. | ||
|
||
### Error Handling | ||
|
||
The tool provides comprehensive error categorization: | ||
|
||
- **Syntax errors**: Malformed GraphQL syntax | ||
- **Field errors**: References to non-existent fields | ||
- **Type errors**: Type-related validation issues | ||
- **Client errors**: Authentication or connectivity issues | ||
- **Rate limit errors**: API rate limiting | ||
- **Permission errors**: Access denied to resources | ||
- **Not found errors**: Referenced resources don't exist | ||
|
||
## Usage with MCP | ||
|
||
This tool is part of the "graphql" toolset and can be enabled through the dynamic toolset system: | ||
|
||
1. Enable the graphql toolset: `enable_toolset` with name "graphql" | ||
2. Use `execute_graphql_query` to run queries and get results | ||
|
||
## Testing | ||
|
||
The tool includes comprehensive tests covering: | ||
|
||
- Tool definition validation | ||
- Required parameter checking | ||
- Response format validation | ||
- Variable handling | ||
- Error categorization | ||
|
||
Run tests with: `go test -v ./pkg/github -run GraphQL` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"annotations": { | ||
"title": "Execute GraphQL query", | ||
"readOnlyHint": false | ||
}, | ||
"description": "Execute a GraphQL query against GitHub's API and return the results.", | ||
"inputSchema": { | ||
"properties": { | ||
"query": { | ||
"description": "The GraphQL query string to execute", | ||
"type": "string" | ||
}, | ||
"variables": { | ||
"description": "Variables for the GraphQL query (optional)", | ||
"properties": {}, | ||
"type": "object" | ||
} | ||
}, | ||
"required": [ | ||
"query" | ||
], | ||
"type": "object" | ||
}, | ||
"name": "execute_graphql_query" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package github | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"net/http" | ||
"testing" | ||
|
||
"github.com/github/github-mcp-server/pkg/translations" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
// TestGraphQLToolsIntegration tests that GraphQL tools can be created and called | ||
func TestGraphQLToolsIntegration(t *testing.T) { | ||
t.Parallel() | ||
|
||
// Create mock clients | ||
mockHTTPClient := &http.Client{} | ||
getClient := stubGetClientFromHTTPFn(mockHTTPClient) | ||
|
||
// Test that we can create execute tool without errors | ||
t.Run("create_tools", func(t *testing.T) { | ||
executeTool, executeHandler := ExecuteGraphQLQuery(getClient, translations.NullTranslationHelper) | ||
|
||
// Verify tool definitions | ||
assert.Equal(t, "execute_graphql_query", executeTool.Name) | ||
assert.NotNil(t, executeHandler) | ||
|
||
// Verify tool schemas have required fields | ||
assert.Contains(t, executeTool.InputSchema.Properties, "query") | ||
assert.Contains(t, executeTool.InputSchema.Properties, "variables") | ||
|
||
// Verify required parameters | ||
assert.Contains(t, executeTool.InputSchema.Required, "query") | ||
}) | ||
|
||
// Test basic invocation of execution tool | ||
t.Run("invoke_execute_tool", func(t *testing.T) { | ||
_, handler := ExecuteGraphQLQuery(getClient, translations.NullTranslationHelper) | ||
|
||
request := createMCPRequest(map[string]any{ | ||
"query": `query { viewer { login } }`, | ||
}) | ||
|
||
result, err := handler(context.Background(), request) | ||
require.NoError(t, err) | ||
require.NotNil(t, result) | ||
|
||
textContent := getTextResult(t, result) | ||
var response map[string]interface{} | ||
err = json.Unmarshal([]byte(textContent.Text), &response) | ||
require.NoError(t, err) | ||
|
||
// Should have basic response structure | ||
assert.Contains(t, response, "query") | ||
assert.Contains(t, response, "variables") | ||
assert.Contains(t, response, "success") | ||
}) | ||
|
||
// Test error handling for missing required parameters | ||
t.Run("error_handling", func(t *testing.T) { | ||
_, executeHandler := ExecuteGraphQLQuery(getClient, translations.NullTranslationHelper) | ||
|
||
emptyRequest := createMCPRequest(map[string]any{}) | ||
|
||
// Execute tool should handle missing query parameter | ||
executeResult, err := executeHandler(context.Background(), emptyRequest) | ||
require.NoError(t, err) | ||
textContent := getTextResult(t, executeResult) | ||
assert.Contains(t, textContent.Text, "query") | ||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
package github | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/github/github-mcp-server/pkg/translations" | ||
"github.com/mark3labs/mcp-go/mcp" | ||
"github.com/mark3labs/mcp-go/server" | ||
) | ||
|
||
// ExecuteGraphQLQuery creates a tool to execute a GraphQL query and return results | ||
func ExecuteGraphQLQuery(getClient GetClientFn, t translations.TranslationHelperFunc) (tool mcp.Tool, handler server.ToolHandlerFunc) { | ||
return mcp.NewTool("execute_graphql_query", | ||
mcp.WithDescription(t("TOOL_EXECUTE_GRAPHQL_QUERY_DESCRIPTION", "Execute a GraphQL query against GitHub's API and return the results.")), | ||
mcp.WithToolAnnotation(mcp.ToolAnnotation{ | ||
Title: t("TOOL_EXECUTE_GRAPHQL_QUERY_USER_TITLE", "Execute GraphQL query"), | ||
ReadOnlyHint: ToBoolPtr(false), | ||
}), | ||
mcp.WithString("query", | ||
mcp.Required(), | ||
mcp.Description("The GraphQL query string to execute"), | ||
), | ||
mcp.WithObject("variables", | ||
mcp.Description("Variables for the GraphQL query (optional)"), | ||
), | ||
), | ||
func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { | ||
queryStr, err := RequiredParam[string](request, "query") | ||
if err != nil { | ||
return mcp.NewToolResultError(err.Error()), nil | ||
} | ||
|
||
variables, _ := OptionalParam[map[string]interface{}](request, "variables") | ||
if variables == nil { | ||
variables = make(map[string]interface{}) | ||
} | ||
|
||
client, err := getClient(ctx) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to get GitHub client: %w", err) | ||
} | ||
|
||
// Create a GraphQL request payload | ||
graphqlPayload := map[string]interface{}{ | ||
"query": queryStr, | ||
"variables": variables, | ||
} | ||
|
||
// Use the underlying HTTP client to make a raw GraphQL request | ||
req, err := client.NewRequest("POST", "graphql", graphqlPayload) | ||
if err != nil { | ||
return mcp.NewToolResultError(fmt.Sprintf("failed to create request: %v", err)), nil | ||
} | ||
|
||
// Execute the request | ||
var response map[string]interface{} | ||
_, err = client.Do(ctx, req, &response) | ||
|
||
result := map[string]interface{}{ | ||
"query": queryStr, | ||
"variables": variables, | ||
} | ||
|
||
if err != nil { | ||
// Query execution failed | ||
result["success"] = false | ||
result["error"] = err.Error() | ||
|
||
// Try to categorize the error | ||
errorStr := err.Error() | ||
switch { | ||
case strings.Contains(errorStr, "rate limit"): | ||
result["error_type"] = "rate_limit" | ||
case strings.Contains(errorStr, "unauthorized") || strings.Contains(errorStr, "authentication"): | ||
result["error_type"] = "authentication" | ||
case strings.Contains(errorStr, "permission") || strings.Contains(errorStr, "forbidden"): | ||
result["error_type"] = "permission" | ||
case strings.Contains(errorStr, "not found") || strings.Contains(errorStr, "Could not resolve") || strings.Contains(errorStr, "not exist"): | ||
result["error_type"] = "not_found" | ||
default: | ||
result["error_type"] = "execution_error" | ||
} | ||
} else { | ||
// Query executed successfully | ||
result["success"] = true | ||
result["data"] = response["data"] | ||
|
||
// Include any errors from the GraphQL response | ||
if errors, ok := response["errors"]; ok { | ||
result["graphql_errors"] = errors | ||
} | ||
} | ||
|
||
r, err := json.Marshal(result) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to marshal response: %w", err) | ||
} | ||
|
||
return mcp.NewToolResultText(string(r)), nil | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.