| {"repo_name": "github-mcp-server", "file_name": "/github-mcp-server/internal/githubv4mock/githubv4mock.go", "inference_info": {"prefix_code": "// githubv4mock package provides a mock GraphQL server used for testing queries produced via\n// shurcooL/githubv4 or shurcooL/graphql modules.\npackage githubv4mock\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n)\n\ntype Matcher struct {\n\tRequest string\n\tVariables map[string]any\n\n\tResponse GQLResponse\n}\n\n// NewQueryMatcher constructs a new matcher for the provided query and variables.\n// If the provided query is a string, it will be used-as-is, otherwise it will be\n// converted to a string using the constructQuery function taken from shurcooL/graphql.\nfunc NewQueryMatcher(query any, variables map[string]any, response GQLResponse) Matcher {\n\tqueryString, ok := query.(string)\n\tif !ok {\n\t\tqueryString = constructQuery(query, variables)\n\t}\n\n\treturn Matcher{\n\t\tRequest: queryString,\n\t\tVariables: variables,\n\t\tResponse: response,\n\t}\n}\n\n// NewMutationMatcher constructs a new matcher for the provided mutation and variables.\n// If the provided mutation is a string, it will be used-as-is, otherwise it will be\n// converted to a string using the constructMutation function taken from shurcooL/graphql.\n//\n// The input parameter is a special form of variable, matching the usage in shurcooL/githubv4. It will be added\n// to the query as a variable called `input`. Furthermore, it will be converted to a map[string]any\n// to be used for later equality comparison, as when the http handler is called, the request body will no longer\n// contain the input struct type information.\nfunc NewMutationMatcher(mutation any, input any, variables map[string]any, response GQLResponse) Matcher {\n\tmutationString, ok := mutation.(string)\n\tif !ok {\n\t\t// Matching shurcooL/githubv4 mutation behaviour found in https://github.com/shurcooL/githubv4/blob/48295856cce734663ddbd790ff54800f784f3193/githubv4.go#L45-L56\n\t\tif variables == nil {\n\t\t\tvariables = map[string]any{\"input\": input}\n\t\t} else {\n\t\t\tvariables[\"input\"] = input\n\t\t}\n\n\t\tmutationString = constructMutation(mutation, variables)\n\t\tm, _ := githubv4InputStructToMap(input)\n\t\tvariables[\"input\"] = m\n\t}\n\n\t", "suffix_code": "\n}\n\ntype GQLResponse struct {\n\tData map[string]any `json:\"data\"`\n\tErrors []struct {\n\t\tMessage string `json:\"message\"`\n\t} `json:\"errors,omitempty\"`\n}\n\n// DataResponse is the happy path response constructor for a mocked GraphQL request.\nfunc DataResponse(data map[string]any) GQLResponse {\n\treturn GQLResponse{\n\t\tData: data,\n\t}\n}\n\n// ErrorResponse is the unhappy path response constructor for a mocked GraphQL request.\\\n// Note that for the moment it is only possible to return a single error message.\nfunc ErrorResponse(errorMsg string) GQLResponse {\n\treturn GQLResponse{\n\t\tErrors: []struct {\n\t\t\tMessage string `json:\"message\"`\n\t\t}{\n\t\t\t{\n\t\t\t\tMessage: errorMsg,\n\t\t\t},\n\t\t},\n\t}\n}\n\n// githubv4InputStructToMap converts a struct to a map[string]any, it uses JSON marshalling rather than reflection\n// to do so, because the json struct tags are used in the real implementation to produce the variable key names,\n// and we need to ensure that when variable matching occurs in the http handler, the keys correctly match.\nfunc githubv4InputStructToMap(s any) (map[string]any, error) {\n\tjsonBytes, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result map[string]any\n\terr = json.Unmarshal(jsonBytes, &result)\n\treturn result, err\n}\n\n// NewMockedHTTPClient creates a new HTTP client that registers a handler for /graphql POST requests.\n// For each request, an attempt will be be made to match the request body against the provided matchers.\n// If a match is found, the corresponding response will be returned with StatusOK.\n//\n// Note that query and variable matching can be slightly fickle. The client expects an EXACT match on the query,\n// which in most cases will have been constructed from a type with graphql tags. The query construction code in\n// shurcooL/githubv4 uses the field types to derive the query string, thus a go string is not the same as a graphql.ID,\n// even though `type ID string`. It is therefore expected that matching variables have the right type for example:\n//\n//\tgithubv4mock.NewQueryMatcher(\n//\t struct {\n//\t Repository struct {\n//\t PullRequest struct {\n//\t ID githubv4.ID\n//\t } `graphql:\"pullRequest(number: $prNum)\"`\n//\t } `graphql:\"repository(owner: $owner, name: $repo)\"`\n//\t }{},\n//\t map[string]any{\n//\t \"owner\": githubv4.String(\"owner\"),\n//\t \"repo\": githubv4.String(\"repo\"),\n//\t \"prNum\": githubv4.Int(42),\n//\t },\n//\t githubv4mock.DataResponse(\n//\t map[string]any{\n//\t \"repository\": map[string]any{\n//\t \"pullRequest\": map[string]any{\n//\t \"id\": \"PR_kwDODKw3uc6WYN1T\",\n//\t },\n//\t },\n//\t },\n//\t ),\n//\t)\n//\n// To aid in variable equality checks, values are considered equal if they approximate to the same type. This is\n// required because when the http handler is called, the request body no longer has the type information. This manifests\n// particularly when using the githubv4.Input types which have type deffed fields in their structs. For example:\n//\n//\ttype CloseIssueInput struct {\n//\t IssueID ID `json:\"issueId\"`\n//\t StateReason *IssueClosedStateReason `json:\"stateReason,omitempty\"`\n//\t}\n//\n// This client does not currently provide a mechanism for out-of-band errors e.g. returning a 500,\n// and errors are constrained to GQL errors returned in the response body with a 200 status code.\nfunc NewMockedHTTPClient(ms ...Matcher) *http.Client {\n\tmatchers := make(map[string]Matcher, len(ms))\n\tfor _, m := range ms {\n\t\tmatchers[m.Request] = m\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/graphql\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\thttp.Error(w, \"method not allowed\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\tgqlRequest, err := parseBody(r.Body)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"invalid request body\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tdefer func() { _ = r.Body.Close() }()\n\n\t\tmatcher, ok := matchers[gqlRequest.Query]\n\t\tif !ok {\n\t\t\thttp.Error(w, fmt.Sprintf(\"no matcher found for query %s\", gqlRequest.Query), http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tif len(gqlRequest.Variables) > 0 {\n\t\t\tif len(gqlRequest.Variables) != len(matcher.Variables) {\n\t\t\t\thttp.Error(w, \"variables do not have the same length\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor k, v := range matcher.Variables {\n\t\t\t\tif !objectsAreEqualValues(v, gqlRequest.Variables[k]) {\n\t\t\t\t\thttp.Error(w, \"variable does not match\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tresponseBody, err := json.Marshal(matcher.Response)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error marshalling response\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, _ = w.Write(responseBody)\n\t})\n\n\treturn &http.Client{Transport: &localRoundTripper{\n\t\thandler: mux,\n\t}}\n}\n\ntype gqlRequest struct {\n\tQuery string `json:\"query\"`\n\tVariables map[string]any `json:\"variables,omitempty\"`\n}\n\nfunc parseBody(r io.Reader) (gqlRequest, error) {\n\tvar req gqlRequest\n\terr := json.NewDecoder(r).Decode(&req)\n\treturn req, err\n}\n\nfunc Ptr[T any](v T) *T { return &v }\n", "middle_code": "return Matcher{\n\t\tRequest: mutationString,\n\t\tVariables: variables,\n\t\tResponse: response,\n\t}", "code_description": null, "fill_type": "LINE_TYPE", "language_type": "go", "sub_task_type": "return_statement"}, "context_code": [["/github-mcp-server/internal/githubv4mock/query.go", "// Ths contents of this file are taken from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/query.go\n// because they are not exported by the module, and we would like to use them in building the githubv4mock test utility.\n//\n// The original license, copied from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/LICENSE\n//\n// MIT License\n\n// Copyright (c) 2017 Dmitri Shuralyov\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\npackage githubv4mock\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"reflect\"\n\t\"sort\"\n\n\t\"github.com/shurcooL/graphql/ident\"\n)\n\nfunc constructQuery(v any, variables map[string]any) string {\n\tquery := query(v)\n\tif len(variables) > 0 {\n\t\treturn \"query(\" + queryArguments(variables) + \")\" + query\n\t}\n\treturn query\n}\n\nfunc constructMutation(v any, variables map[string]any) string {\n\tquery := query(v)\n\tif len(variables) > 0 {\n\t\treturn \"mutation(\" + queryArguments(variables) + \")\" + query\n\t}\n\treturn \"mutation\" + query\n}\n\n// queryArguments constructs a minified arguments string for variables.\n//\n// E.g., map[string]any{\"a\": Int(123), \"b\": NewBoolean(true)} -> \"$a:Int!$b:Boolean\".\nfunc queryArguments(variables map[string]any) string {\n\t// Sort keys in order to produce deterministic output for testing purposes.\n\t// TODO: If tests can be made to work with non-deterministic output, then no need to sort.\n\tkeys := make([]string, 0, len(variables))\n\tfor k := range variables {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tvar buf bytes.Buffer\n\tfor _, k := range keys {\n\t\t_, _ = io.WriteString(&buf, \"$\")\n\t\t_, _ = io.WriteString(&buf, k)\n\t\t_, _ = io.WriteString(&buf, \":\")\n\t\twriteArgumentType(&buf, reflect.TypeOf(variables[k]), true)\n\t\t// Don't insert a comma here.\n\t\t// Commas in GraphQL are insignificant, and we want minified output.\n\t\t// See https://spec.graphql.org/October2021/#sec-Insignificant-Commas.\n\t}\n\treturn buf.String()\n}\n\n// writeArgumentType writes a minified GraphQL type for t to w.\n// value indicates whether t is a value (required) type or pointer (optional) type.\n// If value is true, then \"!\" is written at the end of t.\nfunc writeArgumentType(w io.Writer, t reflect.Type, value bool) {\n\tif t.Kind() == reflect.Ptr {\n\t\t// Pointer is an optional type, so no \"!\" at the end of the pointer's underlying type.\n\t\twriteArgumentType(w, t.Elem(), false)\n\t\treturn\n\t}\n\n\tswitch t.Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\t// List. E.g., \"[Int]\".\n\t\t_, _ = io.WriteString(w, \"[\")\n\t\twriteArgumentType(w, t.Elem(), true)\n\t\t_, _ = io.WriteString(w, \"]\")\n\tdefault:\n\t\t// Named type. E.g., \"Int\".\n\t\tname := t.Name()\n\t\tif name == \"string\" { // HACK: Workaround for https://github.com/shurcooL/githubv4/issues/12.\n\t\t\tname = \"ID\"\n\t\t}\n\t\t_, _ = io.WriteString(w, name)\n\t}\n\n\tif value {\n\t\t// Value is a required type, so add \"!\" to the end.\n\t\t_, _ = io.WriteString(w, \"!\")\n\t}\n}\n\n// query uses writeQuery to recursively construct\n// a minified query string from the provided struct v.\n//\n// E.g., struct{Foo Int, BarBaz *Boolean} -> \"{foo,barBaz}\".\nfunc query(v any) string {\n\tvar buf bytes.Buffer\n\twriteQuery(&buf, reflect.TypeOf(v), false)\n\treturn buf.String()\n}\n\n// writeQuery writes a minified query for t to w.\n// If inline is true, the struct fields of t are inlined into parent struct.\nfunc writeQuery(w io.Writer, t reflect.Type, inline bool) {\n\tswitch t.Kind() {\n\tcase reflect.Ptr, reflect.Slice:\n\t\twriteQuery(w, t.Elem(), false)\n\tcase reflect.Struct:\n\t\t// If the type implements json.Unmarshaler, it's a scalar. Don't expand it.\n\t\tif reflect.PointerTo(t).Implements(jsonUnmarshaler) {\n\t\t\treturn\n\t\t}\n\t\tif !inline {\n\t\t\t_, _ = io.WriteString(w, \"{\")\n\t\t}\n\t\tfor i := 0; i < t.NumField(); i++ {\n\t\t\tif i != 0 {\n\t\t\t\t_, _ = io.WriteString(w, \",\")\n\t\t\t}\n\t\t\tf := t.Field(i)\n\t\t\tvalue, ok := f.Tag.Lookup(\"graphql\")\n\t\t\tinlineField := f.Anonymous && !ok\n\t\t\tif !inlineField {\n\t\t\t\tif ok {\n\t\t\t\t\t_, _ = io.WriteString(w, value)\n\t\t\t\t} else {\n\t\t\t\t\t_, _ = io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase())\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteQuery(w, f.Type, inlineField)\n\t\t}\n\t\tif !inline {\n\t\t\t_, _ = io.WriteString(w, \"}\")\n\t\t}\n\t}\n}\n\nvar jsonUnmarshaler = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()\n"], ["/github-mcp-server/cmd/mcpcurl/main.go", "package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math/big\"\n\t\"os\"\n\t\"os/exec\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\ntype (\n\t// SchemaResponse represents the top-level response containing tools\n\tSchemaResponse struct {\n\t\tResult Result `json:\"result\"`\n\t\tJSONRPC string `json:\"jsonrpc\"`\n\t\tID int `json:\"id\"`\n\t}\n\n\t// Result contains the list of available tools\n\tResult struct {\n\t\tTools []Tool `json:\"tools\"`\n\t}\n\n\t// Tool represents a single command with its schema\n\tTool struct {\n\t\tName string `json:\"name\"`\n\t\tDescription string `json:\"description\"`\n\t\tInputSchema InputSchema `json:\"inputSchema\"`\n\t}\n\n\t// InputSchema defines the structure of a tool's input parameters\n\tInputSchema struct {\n\t\tType string `json:\"type\"`\n\t\tProperties map[string]Property `json:\"properties\"`\n\t\tRequired []string `json:\"required\"`\n\t\tAdditionalProperties bool `json:\"additionalProperties\"`\n\t\tSchema string `json:\"$schema\"`\n\t}\n\n\t// Property defines a single parameter's type and constraints\n\tProperty struct {\n\t\tType string `json:\"type\"`\n\t\tDescription string `json:\"description\"`\n\t\tEnum []string `json:\"enum,omitempty\"`\n\t\tMinimum *float64 `json:\"minimum,omitempty\"`\n\t\tMaximum *float64 `json:\"maximum,omitempty\"`\n\t\tItems *PropertyItem `json:\"items,omitempty\"`\n\t}\n\n\t// PropertyItem defines the type of items in an array property\n\tPropertyItem struct {\n\t\tType string `json:\"type\"`\n\t\tProperties map[string]Property `json:\"properties,omitempty\"`\n\t\tRequired []string `json:\"required,omitempty\"`\n\t\tAdditionalProperties bool `json:\"additionalProperties,omitempty\"`\n\t}\n\n\t// JSONRPCRequest represents a JSON-RPC 2.0 request\n\tJSONRPCRequest struct {\n\t\tJSONRPC string `json:\"jsonrpc\"`\n\t\tID int `json:\"id\"`\n\t\tMethod string `json:\"method\"`\n\t\tParams RequestParams `json:\"params\"`\n\t}\n\n\t// RequestParams contains the tool name and arguments\n\tRequestParams struct {\n\t\tName string `json:\"name\"`\n\t\tArguments map[string]interface{} `json:\"arguments\"`\n\t}\n\n\t// Content matches the response format of a text content response\n\tContent struct {\n\t\tType string `json:\"type\"`\n\t\tText string `json:\"text\"`\n\t}\n\n\tResponseResult struct {\n\t\tContent []Content `json:\"content\"`\n\t}\n\n\tResponse struct {\n\t\tResult ResponseResult `json:\"result\"`\n\t\tJSONRPC string `json:\"jsonrpc\"`\n\t\tID int `json:\"id\"`\n\t}\n)\n\nvar (\n\t// Create root command\n\trootCmd = &cobra.Command{\n\t\tUse: \"mcpcurl\",\n\t\tShort: \"CLI tool with dynamically generated commands\",\n\t\tLong: \"A CLI tool for interacting with MCP API based on dynamically loaded schemas\",\n\t\tPersistentPreRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\t// Skip validation for help and completion commands\n\t\t\tif cmd.Name() == \"help\" || cmd.Name() == \"completion\" {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// Check if the required global flag is provided\n\t\t\tserverCmd, _ := cmd.Flags().GetString(\"stdio-server-cmd\")\n\t\t\tif serverCmd == \"\" {\n\t\t\t\treturn fmt.Errorf(\"--stdio-server-cmd is required\")\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\t// Add schema command\n\tschemaCmd = &cobra.Command{\n\t\tUse: \"schema\",\n\t\tShort: \"Fetch schema from MCP server\",\n\t\tLong: \"Fetches the tools schema from the MCP server specified by --stdio-server-cmd\",\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tserverCmd, _ := cmd.Flags().GetString(\"stdio-server-cmd\")\n\t\t\tif serverCmd == \"\" {\n\t\t\t\treturn fmt.Errorf(\"--stdio-server-cmd is required\")\n\t\t\t}\n\n\t\t\t// Build the JSON-RPC request for tools/list\n\t\t\tjsonRequest, err := buildJSONRPCRequest(\"tools/list\", \"\", nil)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to build JSON-RPC request: %w\", err)\n\t\t\t}\n\n\t\t\t// Execute the server command and pass the JSON-RPC request\n\t\t\tresponse, err := executeServerCommand(serverCmd, jsonRequest)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error executing server command: %w\", err)\n\t\t\t}\n\n\t\t\t// Output the response\n\t\t\tfmt.Println(response)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\t// Create the tools command\n\ttoolsCmd = &cobra.Command{\n\t\tUse: \"tools\",\n\t\tShort: \"Access available tools\",\n\t\tLong: \"Contains all dynamically generated tool commands from the schema\",\n\t}\n)\n\nfunc main() {\n\trootCmd.AddCommand(schemaCmd)\n\n\t// Add global flag for stdio server command\n\trootCmd.PersistentFlags().String(\"stdio-server-cmd\", \"\", \"Shell command to invoke MCP server via stdio (required)\")\n\t_ = rootCmd.MarkPersistentFlagRequired(\"stdio-server-cmd\")\n\n\t// Add global flag for pretty printing\n\trootCmd.PersistentFlags().Bool(\"pretty\", true, \"Pretty print MCP response (only for JSON or JSONL responses)\")\n\n\t// Add the tools command to the root command\n\trootCmd.AddCommand(toolsCmd)\n\n\t// Execute the root command once to parse flags\n\t_ = rootCmd.ParseFlags(os.Args[1:])\n\n\t// Get pretty flag\n\tprettyPrint, err := rootCmd.Flags().GetBool(\"pretty\")\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Error getting pretty flag: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\t// Get server command\n\tserverCmd, err := rootCmd.Flags().GetString(\"stdio-server-cmd\")\n\tif err == nil && serverCmd != \"\" {\n\t\t// Fetch schema from server\n\t\tjsonRequest, err := buildJSONRPCRequest(\"tools/list\", \"\", nil)\n\t\tif err == nil {\n\t\t\tresponse, err := executeServerCommand(serverCmd, jsonRequest)\n\t\t\tif err == nil {\n\t\t\t\t// Parse the schema response\n\t\t\t\tvar schemaResp SchemaResponse\n\t\t\t\tif err := json.Unmarshal([]byte(response), &schemaResp); err == nil {\n\t\t\t\t\t// Add all the generated commands as subcommands of tools\n\t\t\t\t\tfor _, tool := range schemaResp.Result.Tools {\n\t\t\t\t\t\taddCommandFromTool(toolsCmd, &tool, prettyPrint)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Execute\n\tif err := rootCmd.Execute(); err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Error executing command: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\n// addCommandFromTool creates a cobra command from a tool schema\nfunc addCommandFromTool(toolsCmd *cobra.Command, tool *Tool, prettyPrint bool) {\n\t// Create command from tool\n\tcmd := &cobra.Command{\n\t\tUse: tool.Name,\n\t\tShort: tool.Description,\n\t\tRun: func(cmd *cobra.Command, _ []string) {\n\t\t\t// Build a map of arguments from flags\n\t\t\targuments, err := buildArgumentsMap(cmd, tool)\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"failed to build arguments map: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tjsonData, err := buildJSONRPCRequest(\"tools/call\", tool.Name, arguments)\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"failed to build JSONRPC request: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Execute the server command\n\t\t\tserverCmd, err := cmd.Flags().GetString(\"stdio-server-cmd\")\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"failed to get stdio-server-cmd: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresponse, err := executeServerCommand(serverCmd, jsonData)\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"error executing server command: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := printResponse(response, prettyPrint); err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"error printing response: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t},\n\t}\n\n\t// Initialize viper for this command\n\tviperInit := func() {\n\t\tviper.Reset()\n\t\tviper.AutomaticEnv()\n\t\tviper.SetEnvPrefix(strings.ToUpper(tool.Name))\n\t\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\t}\n\n\t// We'll call the init function directly instead of with cobra.OnInitialize\n\t// to avoid conflicts between commands\n\tviperInit()\n\n\t// Add flags based on schema properties\n\tfor name, prop := range tool.InputSchema.Properties {\n\t\tisRequired := slices.Contains(tool.InputSchema.Required, name)\n\n\t\t// Enhance description to indicate if parameter is optional\n\t\tdescription := prop.Description\n\t\tif !isRequired {\n\t\t\tdescription += \" (optional)\"\n\t\t}\n\n\t\tswitch prop.Type {\n\t\tcase \"string\":\n\t\t\tcmd.Flags().String(name, \"\", description)\n\t\t\tif len(prop.Enum) > 0 {\n\t\t\t\t// Add validation in PreRun for enum values\n\t\t\t\tcmd.PreRunE = func(cmd *cobra.Command, _ []string) error {\n\t\t\t\t\tfor flagName, property := range tool.InputSchema.Properties {\n\t\t\t\t\t\tif len(property.Enum) > 0 {\n\t\t\t\t\t\t\tvalue, _ := cmd.Flags().GetString(flagName)\n\t\t\t\t\t\t\tif value != \"\" && !slices.Contains(property.Enum, value) {\n\t\t\t\t\t\t\t\treturn fmt.Errorf(\"%s must be one of: %s\", flagName, strings.Join(property.Enum, \", \"))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"number\":\n\t\t\tcmd.Flags().Float64(name, 0, description)\n\t\tcase \"integer\":\n\t\t\tcmd.Flags().Int64(name, 0, description)\n\t\tcase \"boolean\":\n\t\t\tcmd.Flags().Bool(name, false, description)\n\t\tcase \"array\":\n\t\t\tif prop.Items != nil {\n\t\t\t\tswitch prop.Items.Type {\n\t\t\t\tcase \"string\":\n\t\t\t\t\tcmd.Flags().StringSlice(name, []string{}, description)\n\t\t\t\tcase \"object\":\n\t\t\t\t\tcmd.Flags().String(name+\"-json\", \"\", description+\" (provide as JSON array)\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif isRequired {\n\t\t\t_ = cmd.MarkFlagRequired(name)\n\t\t}\n\n\t\t// Bind flag to viper\n\t\t_ = viper.BindPFlag(name, cmd.Flags().Lookup(name))\n\t}\n\n\t// Add command to root\n\ttoolsCmd.AddCommand(cmd)\n}\n\n// buildArgumentsMap extracts flag values into a map of arguments\nfunc buildArgumentsMap(cmd *cobra.Command, tool *Tool) (map[string]interface{}, error) {\n\targuments := make(map[string]interface{})\n\n\tfor name, prop := range tool.InputSchema.Properties {\n\t\tswitch prop.Type {\n\t\tcase \"string\":\n\t\t\tif value, _ := cmd.Flags().GetString(name); value != \"\" {\n\t\t\t\targuments[name] = value\n\t\t\t}\n\t\tcase \"number\":\n\t\t\tif value, _ := cmd.Flags().GetFloat64(name); value != 0 {\n\t\t\t\targuments[name] = value\n\t\t\t}\n\t\tcase \"integer\":\n\t\t\tif value, _ := cmd.Flags().GetInt64(name); value != 0 {\n\t\t\t\targuments[name] = value\n\t\t\t}\n\t\tcase \"boolean\":\n\t\t\t// For boolean, we need to check if it was explicitly set\n\t\t\tif cmd.Flags().Changed(name) {\n\t\t\t\tvalue, _ := cmd.Flags().GetBool(name)\n\t\t\t\targuments[name] = value\n\t\t\t}\n\t\tcase \"array\":\n\t\t\tif prop.Items != nil {\n\t\t\t\tswitch prop.Items.Type {\n\t\t\t\tcase \"string\":\n\t\t\t\t\tif values, _ := cmd.Flags().GetStringSlice(name); len(values) > 0 {\n\t\t\t\t\t\targuments[name] = values\n\t\t\t\t\t}\n\t\t\t\tcase \"object\":\n\t\t\t\t\tif jsonStr, _ := cmd.Flags().GetString(name + \"-json\"); jsonStr != \"\" {\n\t\t\t\t\t\tvar jsonArray []interface{}\n\t\t\t\t\t\tif err := json.Unmarshal([]byte(jsonStr), &jsonArray); err != nil {\n\t\t\t\t\t\t\treturn nil, fmt.Errorf(\"error parsing JSON for %s: %w\", name, err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\targuments[name] = jsonArray\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arguments, nil\n}\n\n// buildJSONRPCRequest creates a JSON-RPC request with the given tool name and arguments\nfunc buildJSONRPCRequest(method, toolName string, arguments map[string]interface{}) (string, error) {\n\tid, err := rand.Int(rand.Reader, big.NewInt(10000))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to generate random ID: %w\", err)\n\t}\n\trequest := JSONRPCRequest{\n\t\tJSONRPC: \"2.0\",\n\t\tID: int(id.Int64()), // Random ID between 0 and 9999\n\t\tMethod: method,\n\t\tParams: RequestParams{\n\t\t\tName: toolName,\n\t\t\tArguments: arguments,\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal JSON request: %w\", err)\n\t}\n\treturn string(jsonData), nil\n}\n\n// executeServerCommand runs the specified command, sends the JSON request to stdin,\n// and returns the response from stdout\nfunc executeServerCommand(cmdStr, jsonRequest string) (string, error) {\n\t// Split the command string into command and arguments\n\tcmdParts := strings.Fields(cmdStr)\n\tif len(cmdParts) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty command\")\n\t}\n\n\tcmd := exec.Command(cmdParts[0], cmdParts[1:]...) //nolint:gosec //mcpcurl is a test command that needs to execute arbitrary shell commands\n\n\t// Setup stdin pipe\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create stdin pipe: %w\", err)\n\t}\n\n\t// Setup stdout and stderr pipes\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\t// Start the command\n\tif err := cmd.Start(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to start command: %w\", err)\n\t}\n\n\t// Write the JSON request to stdin\n\tif _, err := io.WriteString(stdin, jsonRequest+\"\\n\"); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to write to stdin: %w\", err)\n\t}\n\t_ = stdin.Close()\n\n\t// Wait for the command to complete\n\tif err := cmd.Wait(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"command failed: %w, stderr: %s\", err, stderr.String())\n\t}\n\n\treturn stdout.String(), nil\n}\n\nfunc printResponse(response string, prettyPrint bool) error {\n\tif !prettyPrint {\n\t\tfmt.Println(response)\n\t\treturn nil\n\t}\n\n\t// Parse the JSON response\n\tvar resp Response\n\tif err := json.Unmarshal([]byte(response), &resp); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse JSON: %w\", err)\n\t}\n\n\t// Extract text from content items of type \"text\"\n\tfor _, content := range resp.Result.Content {\n\t\tif content.Type == \"text\" {\n\t\t\tvar textContentObj map[string]interface{}\n\t\t\terr := json.Unmarshal([]byte(content.Text), &textContentObj)\n\n\t\t\tif err == nil {\n\t\t\t\tprettyText, err := json.MarshalIndent(textContentObj, \"\", \" \")\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to pretty print text content: %w\", err)\n\t\t\t\t}\n\t\t\t\tfmt.Println(string(prettyText))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Fallback parsing as JSONL\n\t\t\tvar textContentList []map[string]interface{}\n\t\t\tif err := json.Unmarshal([]byte(content.Text), &textContentList); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to parse text content as a list: %w\", err)\n\t\t\t}\n\t\t\tprettyText, err := json.MarshalIndent(textContentList, \"\", \" \")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to pretty print array content: %w\", err)\n\t\t\t}\n\t\t\tfmt.Println(string(prettyText))\n\t\t}\n\t}\n\n\t// If no text content found, print the original response\n\tif len(resp.Result.Content) == 0 {\n\t\tfmt.Println(response)\n\t}\n\n\treturn nil\n}\n"], ["/github-mcp-server/internal/ghmcp/server.go", "package ghmcp\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com/github/github-mcp-server/pkg/errors\"\n\t\"github.com/github/github-mcp-server/pkg/github\"\n\tmcplog \"github.com/github/github-mcp-server/pkg/log\"\n\t\"github.com/github/github-mcp-server/pkg/raw\"\n\t\"github.com/github/github-mcp-server/pkg/translations\"\n\tgogithub \"github.com/google/go-github/v73/github\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n\t\"github.com/mark3labs/mcp-go/server\"\n\t\"github.com/shurcooL/githubv4\"\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype MCPServerConfig struct {\n\t// Version of the server\n\tVersion string\n\n\t// GitHub Host to target for API requests (e.g. github.com or github.enterprise.com)\n\tHost string\n\n\t// GitHub Token to authenticate with the GitHub API\n\tToken string\n\n\t// EnabledToolsets is a list of toolsets to enable\n\t// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#tool-configuration\n\tEnabledToolsets []string\n\n\t// Whether to enable dynamic toolsets\n\t// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#dynamic-tool-discovery\n\tDynamicToolsets bool\n\n\t// ReadOnly indicates if we should only offer read-only tools\n\tReadOnly bool\n\n\t// Translator provides translated text for the server tooling\n\tTranslator translations.TranslationHelperFunc\n}\n\nfunc NewMCPServer(cfg MCPServerConfig) (*server.MCPServer, error) {\n\tapiHost, err := parseAPIHost(cfg.Host)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse API host: %w\", err)\n\t}\n\n\t// Construct our REST client\n\trestClient := gogithub.NewClient(nil).WithAuthToken(cfg.Token)\n\trestClient.UserAgent = fmt.Sprintf(\"github-mcp-server/%s\", cfg.Version)\n\trestClient.BaseURL = apiHost.baseRESTURL\n\trestClient.UploadURL = apiHost.uploadURL\n\n\t// Construct our GraphQL client\n\t// We're using NewEnterpriseClient here unconditionally as opposed to NewClient because we already\n\t// did the necessary API host parsing so that github.com will return the correct URL anyway.\n\tgqlHTTPClient := &http.Client{\n\t\tTransport: &bearerAuthTransport{\n\t\t\ttransport: http.DefaultTransport,\n\t\t\ttoken: cfg.Token,\n\t\t},\n\t} // We're going to wrap the Transport later in beforeInit\n\tgqlClient := githubv4.NewEnterpriseClient(apiHost.graphqlURL.String(), gqlHTTPClient)\n\n\t// When a client send an initialize request, update the user agent to include the client info.\n\tbeforeInit := func(_ context.Context, _ any, message *mcp.InitializeRequest) {\n\t\tuserAgent := fmt.Sprintf(\n\t\t\t\"github-mcp-server/%s (%s/%s)\",\n\t\t\tcfg.Version,\n\t\t\tmessage.Params.ClientInfo.Name,\n\t\t\tmessage.Params.ClientInfo.Version,\n\t\t)\n\n\t\trestClient.UserAgent = userAgent\n\n\t\tgqlHTTPClient.Transport = &userAgentTransport{\n\t\t\ttransport: gqlHTTPClient.Transport,\n\t\t\tagent: userAgent,\n\t\t}\n\t}\n\n\thooks := &server.Hooks{\n\t\tOnBeforeInitialize: []server.OnBeforeInitializeFunc{beforeInit},\n\t\tOnBeforeAny: []server.BeforeAnyHookFunc{\n\t\t\tfunc(ctx context.Context, _ any, _ mcp.MCPMethod, _ any) {\n\t\t\t\t// Ensure the context is cleared of any previous errors\n\t\t\t\t// as context isn't propagated through middleware\n\t\t\t\terrors.ContextWithGitHubErrors(ctx)\n\t\t\t},\n\t\t},\n\t}\n\n\tghServer := github.NewServer(cfg.Version, server.WithHooks(hooks))\n\n\tenabledToolsets := cfg.EnabledToolsets\n\tif cfg.DynamicToolsets {\n\t\t// filter \"all\" from the enabled toolsets\n\t\tenabledToolsets = make([]string, 0, len(cfg.EnabledToolsets))\n\t\tfor _, toolset := range cfg.EnabledToolsets {\n\t\t\tif toolset != \"all\" {\n\t\t\t\tenabledToolsets = append(enabledToolsets, toolset)\n\t\t\t}\n\t\t}\n\t}\n\n\tgetClient := func(_ context.Context) (*gogithub.Client, error) {\n\t\treturn restClient, nil // closing over client\n\t}\n\n\tgetGQLClient := func(_ context.Context) (*githubv4.Client, error) {\n\t\treturn gqlClient, nil // closing over client\n\t}\n\n\tgetRawClient := func(ctx context.Context) (*raw.Client, error) {\n\t\tclient, err := getClient(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get GitHub client: %w\", err)\n\t\t}\n\t\treturn raw.NewClient(client, apiHost.rawURL), nil // closing over client\n\t}\n\n\t// Create default toolsets\n\ttsg := github.DefaultToolsetGroup(cfg.ReadOnly, getClient, getGQLClient, getRawClient, cfg.Translator)\n\terr = tsg.EnableToolsets(enabledToolsets)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to enable toolsets: %w\", err)\n\t}\n\n\t// Register all mcp functionality with the server\n\ttsg.RegisterAll(ghServer)\n\n\tif cfg.DynamicToolsets {\n\t\tdynamic := github.InitDynamicToolset(ghServer, tsg, cfg.Translator)\n\t\tdynamic.RegisterTools(ghServer)\n\t}\n\n\treturn ghServer, nil\n}\n\ntype StdioServerConfig struct {\n\t// Version of the server\n\tVersion string\n\n\t// GitHub Host to target for API requests (e.g. github.com or github.enterprise.com)\n\tHost string\n\n\t// GitHub Token to authenticate with the GitHub API\n\tToken string\n\n\t// EnabledToolsets is a list of toolsets to enable\n\t// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#tool-configuration\n\tEnabledToolsets []string\n\n\t// Whether to enable dynamic toolsets\n\t// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#dynamic-tool-discovery\n\tDynamicToolsets bool\n\n\t// ReadOnly indicates if we should only register read-only tools\n\tReadOnly bool\n\n\t// ExportTranslations indicates if we should export translations\n\t// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#i18n--overriding-descriptions\n\tExportTranslations bool\n\n\t// EnableCommandLogging indicates if we should log commands\n\tEnableCommandLogging bool\n\n\t// Path to the log file if not stderr\n\tLogFilePath string\n}\n\n// RunStdioServer is not concurrent safe.\nfunc RunStdioServer(cfg StdioServerConfig) error {\n\t// Create app context\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\n\tt, dumpTranslations := translations.TranslationHelper()\n\n\tghServer, err := NewMCPServer(MCPServerConfig{\n\t\tVersion: cfg.Version,\n\t\tHost: cfg.Host,\n\t\tToken: cfg.Token,\n\t\tEnabledToolsets: cfg.EnabledToolsets,\n\t\tDynamicToolsets: cfg.DynamicToolsets,\n\t\tReadOnly: cfg.ReadOnly,\n\t\tTranslator: t,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create MCP server: %w\", err)\n\t}\n\n\tstdioServer := server.NewStdioServer(ghServer)\n\n\tlogrusLogger := logrus.New()\n\tif cfg.LogFilePath != \"\" {\n\t\tfile, err := os.OpenFile(cfg.LogFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\n\t\tlogrusLogger.SetLevel(logrus.DebugLevel)\n\t\tlogrusLogger.SetOutput(file)\n\t}\n\tstdLogger := log.New(logrusLogger.Writer(), \"stdioserver\", 0)\n\tstdioServer.SetErrorLogger(stdLogger)\n\n\tif cfg.ExportTranslations {\n\t\t// Once server is initialized, all translations are loaded\n\t\tdumpTranslations()\n\t}\n\n\t// Start listening for messages\n\terrC := make(chan error, 1)\n\tgo func() {\n\t\tin, out := io.Reader(os.Stdin), io.Writer(os.Stdout)\n\n\t\tif cfg.EnableCommandLogging {\n\t\t\tloggedIO := mcplog.NewIOLogger(in, out, logrusLogger)\n\t\t\tin, out = loggedIO, loggedIO\n\t\t}\n\t\t// enable GitHub errors in the context\n\t\tctx := errors.ContextWithGitHubErrors(ctx)\n\t\terrC <- stdioServer.Listen(ctx, in, out)\n\t}()\n\n\t// Output github-mcp-server string\n\t_, _ = fmt.Fprintf(os.Stderr, \"GitHub MCP Server running on stdio\\n\")\n\n\t// Wait for shutdown signal\n\tselect {\n\tcase <-ctx.Done():\n\t\tlogrusLogger.Infof(\"shutting down server...\")\n\tcase err := <-errC:\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error running server: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype apiHost struct {\n\tbaseRESTURL *url.URL\n\tgraphqlURL *url.URL\n\tuploadURL *url.URL\n\trawURL *url.URL\n}\n\nfunc newDotcomHost() (apiHost, error) {\n\tbaseRestURL, err := url.Parse(\"https://api.github.com/\")\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse dotcom REST URL: %w\", err)\n\t}\n\n\tgqlURL, err := url.Parse(\"https://api.github.com/graphql\")\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse dotcom GraphQL URL: %w\", err)\n\t}\n\n\tuploadURL, err := url.Parse(\"https://uploads.github.com\")\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse dotcom Upload URL: %w\", err)\n\t}\n\n\trawURL, err := url.Parse(\"https://raw.githubusercontent.com/\")\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse dotcom Raw URL: %w\", err)\n\t}\n\n\treturn apiHost{\n\t\tbaseRESTURL: baseRestURL,\n\t\tgraphqlURL: gqlURL,\n\t\tuploadURL: uploadURL,\n\t\trawURL: rawURL,\n\t}, nil\n}\n\nfunc newGHECHost(hostname string) (apiHost, error) {\n\tu, err := url.Parse(hostname)\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHEC URL: %w\", err)\n\t}\n\n\t// Unsecured GHEC would be an error\n\tif u.Scheme == \"http\" {\n\t\treturn apiHost{}, fmt.Errorf(\"GHEC URL must be HTTPS\")\n\t}\n\n\trestURL, err := url.Parse(fmt.Sprintf(\"https://api.%s/\", u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHEC REST URL: %w\", err)\n\t}\n\n\tgqlURL, err := url.Parse(fmt.Sprintf(\"https://api.%s/graphql\", u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHEC GraphQL URL: %w\", err)\n\t}\n\n\tuploadURL, err := url.Parse(fmt.Sprintf(\"https://uploads.%s\", u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHEC Upload URL: %w\", err)\n\t}\n\n\trawURL, err := url.Parse(fmt.Sprintf(\"https://raw.%s/\", u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHEC Raw URL: %w\", err)\n\t}\n\n\treturn apiHost{\n\t\tbaseRESTURL: restURL,\n\t\tgraphqlURL: gqlURL,\n\t\tuploadURL: uploadURL,\n\t\trawURL: rawURL,\n\t}, nil\n}\n\nfunc newGHESHost(hostname string) (apiHost, error) {\n\tu, err := url.Parse(hostname)\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHES URL: %w\", err)\n\t}\n\n\trestURL, err := url.Parse(fmt.Sprintf(\"%s://%s/api/v3/\", u.Scheme, u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHES REST URL: %w\", err)\n\t}\n\n\tgqlURL, err := url.Parse(fmt.Sprintf(\"%s://%s/api/graphql\", u.Scheme, u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHES GraphQL URL: %w\", err)\n\t}\n\n\tuploadURL, err := url.Parse(fmt.Sprintf(\"%s://%s/api/uploads/\", u.Scheme, u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHES Upload URL: %w\", err)\n\t}\n\trawURL, err := url.Parse(fmt.Sprintf(\"%s://%s/raw/\", u.Scheme, u.Hostname()))\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"failed to parse GHES Raw URL: %w\", err)\n\t}\n\n\treturn apiHost{\n\t\tbaseRESTURL: restURL,\n\t\tgraphqlURL: gqlURL,\n\t\tuploadURL: uploadURL,\n\t\trawURL: rawURL,\n\t}, nil\n}\n\n// Note that this does not handle ports yet, so development environments are out.\nfunc parseAPIHost(s string) (apiHost, error) {\n\tif s == \"\" {\n\t\treturn newDotcomHost()\n\t}\n\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\treturn apiHost{}, fmt.Errorf(\"could not parse host as URL: %s\", s)\n\t}\n\n\tif u.Scheme == \"\" {\n\t\treturn apiHost{}, fmt.Errorf(\"host must have a scheme (http or https): %s\", s)\n\t}\n\n\tif strings.HasSuffix(u.Hostname(), \"github.com\") {\n\t\treturn newDotcomHost()\n\t}\n\n\tif strings.HasSuffix(u.Hostname(), \"ghe.com\") {\n\t\treturn newGHECHost(s)\n\t}\n\n\treturn newGHESHost(s)\n}\n\ntype userAgentTransport struct {\n\ttransport http.RoundTripper\n\tagent string\n}\n\nfunc (t *userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = req.Clone(req.Context())\n\treq.Header.Set(\"User-Agent\", t.agent)\n\treturn t.transport.RoundTrip(req)\n}\n\ntype bearerAuthTransport struct {\n\ttransport http.RoundTripper\n\ttoken string\n}\n\nfunc (t *bearerAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = req.Clone(req.Context())\n\treq.Header.Set(\"Authorization\", \"Bearer \"+t.token)\n\treturn t.transport.RoundTrip(req)\n}\n"], ["/github-mcp-server/cmd/github-mcp-server/generate_docs.go", "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/github/github-mcp-server/pkg/github\"\n\t\"github.com/github/github-mcp-server/pkg/raw\"\n\t\"github.com/github/github-mcp-server/pkg/toolsets\"\n\t\"github.com/github/github-mcp-server/pkg/translations\"\n\tgogithub \"github.com/google/go-github/v73/github\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n\t\"github.com/shurcooL/githubv4\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar generateDocsCmd = &cobra.Command{\n\tUse: \"generate-docs\",\n\tShort: \"Generate documentation for tools and toolsets\",\n\tLong: `Generate the automated sections of README.md and docs/remote-server.md with current tool and toolset information.`,\n\tRunE: func(_ *cobra.Command, _ []string) error {\n\t\treturn generateAllDocs()\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(generateDocsCmd)\n}\n\n// mockGetClient returns a mock GitHub client for documentation generation\nfunc mockGetClient(_ context.Context) (*gogithub.Client, error) {\n\treturn gogithub.NewClient(nil), nil\n}\n\n// mockGetGQLClient returns a mock GraphQL client for documentation generation\nfunc mockGetGQLClient(_ context.Context) (*githubv4.Client, error) {\n\treturn githubv4.NewClient(nil), nil\n}\n\n// mockGetRawClient returns a mock raw client for documentation generation\nfunc mockGetRawClient(_ context.Context) (*raw.Client, error) {\n\treturn nil, nil\n}\n\nfunc generateAllDocs() error {\n\tif err := generateReadmeDocs(\"README.md\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to generate README docs: %w\", err)\n\t}\n\n\tif err := generateRemoteServerDocs(\"docs/remote-server.md\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to generate remote-server docs: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc generateReadmeDocs(readmePath string) error {\n\t// Create translation helper\n\tt, _ := translations.TranslationHelper()\n\n\t// Create toolset group with mock clients\n\ttsg := github.DefaultToolsetGroup(false, mockGetClient, mockGetGQLClient, mockGetRawClient, t)\n\n\t// Generate toolsets documentation\n\ttoolsetsDoc := generateToolsetsDoc(tsg)\n\n\t// Generate tools documentation\n\ttoolsDoc := generateToolsDoc(tsg)\n\n\t// Read the current README.md\n\t// #nosec G304 - readmePath is controlled by command line flag, not user input\n\tcontent, err := os.ReadFile(readmePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read README.md: %w\", err)\n\t}\n\n\t// Replace toolsets section\n\tupdatedContent := replaceSection(string(content), \"START AUTOMATED TOOLSETS\", \"END AUTOMATED TOOLSETS\", toolsetsDoc)\n\n\t// Replace tools section\n\tupdatedContent = replaceSection(updatedContent, \"START AUTOMATED TOOLS\", \"END AUTOMATED TOOLS\", toolsDoc)\n\n\t// Write back to file\n\terr = os.WriteFile(readmePath, []byte(updatedContent), 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write README.md: %w\", err)\n\t}\n\n\tfmt.Println(\"Successfully updated README.md with automated documentation\")\n\treturn nil\n}\n\nfunc generateRemoteServerDocs(docsPath string) error {\n\tcontent, err := os.ReadFile(docsPath) //#nosec G304\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read docs file: %w\", err)\n\t}\n\n\ttoolsetsDoc := generateRemoteToolsetsDoc()\n\n\t// Replace content between markers\n\tstartMarker := \"<!-- START AUTOMATED TOOLSETS -->\"\n\tendMarker := \"<!-- END AUTOMATED TOOLSETS -->\"\n\n\tcontentStr := string(content)\n\tstartIndex := strings.Index(contentStr, startMarker)\n\tendIndex := strings.Index(contentStr, endMarker)\n\n\tif startIndex == -1 || endIndex == -1 {\n\t\treturn fmt.Errorf(\"automation markers not found in %s\", docsPath)\n\t}\n\n\tnewContent := contentStr[:startIndex] + startMarker + \"\\n\" + toolsetsDoc + \"\\n\" + endMarker + contentStr[endIndex+len(endMarker):]\n\n\treturn os.WriteFile(docsPath, []byte(newContent), 0600) //#nosec G306\n}\n\nfunc generateToolsetsDoc(tsg *toolsets.ToolsetGroup) string {\n\tvar lines []string\n\n\t// Add table header and separator\n\tlines = append(lines, \"| Toolset | Description |\")\n\tlines = append(lines, \"| ----------------------- | ------------------------------------------------------------- |\")\n\n\t// Add the context toolset row (handled separately in README)\n\tlines = append(lines, \"| `context` | **Strongly recommended**: Tools that provide context about the current user and GitHub context you are operating in |\")\n\n\t// Get all toolsets except context (which is handled separately above)\n\tvar toolsetNames []string\n\tfor name := range tsg.Toolsets {\n\t\tif name != \"context\" && name != \"dynamic\" { // Skip context and dynamic toolsets as they're handled separately\n\t\t\ttoolsetNames = append(toolsetNames, name)\n\t\t}\n\t}\n\n\t// Sort toolset names for consistent output\n\tsort.Strings(toolsetNames)\n\n\tfor _, name := range toolsetNames {\n\t\ttoolset := tsg.Toolsets[name]\n\t\tlines = append(lines, fmt.Sprintf(\"| `%s` | %s |\", name, toolset.Description))\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc generateToolsDoc(tsg *toolsets.ToolsetGroup) string {\n\tvar sections []string\n\n\t// Get all toolset names and sort them alphabetically for deterministic order\n\tvar toolsetNames []string\n\tfor name := range tsg.Toolsets {\n\t\tif name != \"dynamic\" { // Skip dynamic toolset as it's handled separately\n\t\t\ttoolsetNames = append(toolsetNames, name)\n\t\t}\n\t}\n\tsort.Strings(toolsetNames)\n\n\tfor _, toolsetName := range toolsetNames {\n\t\ttoolset := tsg.Toolsets[toolsetName]\n\n\t\ttools := toolset.GetAvailableTools()\n\t\tif len(tools) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sort tools by name for deterministic order\n\t\tsort.Slice(tools, func(i, j int) bool {\n\t\t\treturn tools[i].Tool.Name < tools[j].Tool.Name\n\t\t})\n\n\t\t// Generate section header - capitalize first letter and replace underscores\n\t\tsectionName := formatToolsetName(toolsetName)\n\n\t\tvar toolDocs []string\n\t\tfor _, serverTool := range tools {\n\t\t\ttoolDoc := generateToolDoc(serverTool.Tool)\n\t\t\ttoolDocs = append(toolDocs, toolDoc)\n\t\t}\n\n\t\tif len(toolDocs) > 0 {\n\t\t\tsection := fmt.Sprintf(\"<details>\\n\\n<summary>%s</summary>\\n\\n%s\\n\\n</details>\",\n\t\t\t\tsectionName, strings.Join(toolDocs, \"\\n\\n\"))\n\t\t\tsections = append(sections, section)\n\t\t}\n\t}\n\n\treturn strings.Join(sections, \"\\n\\n\")\n}\n\nfunc formatToolsetName(name string) string {\n\tswitch name {\n\tcase \"pull_requests\":\n\t\treturn \"Pull Requests\"\n\tcase \"repos\":\n\t\treturn \"Repositories\"\n\tcase \"code_security\":\n\t\treturn \"Code Security\"\n\tcase \"secret_protection\":\n\t\treturn \"Secret Protection\"\n\tcase \"orgs\":\n\t\treturn \"Organizations\"\n\tdefault:\n\t\t// Fallback: capitalize first letter and replace underscores with spaces\n\t\tparts := strings.Split(name, \"_\")\n\t\tfor i, part := range parts {\n\t\t\tif len(part) > 0 {\n\t\t\t\tparts[i] = strings.ToUpper(string(part[0])) + part[1:]\n\t\t\t}\n\t\t}\n\t\treturn strings.Join(parts, \" \")\n\t}\n}\n\nfunc generateToolDoc(tool mcp.Tool) string {\n\tvar lines []string\n\n\t// Tool name only (using annotation name instead of verbose description)\n\tlines = append(lines, fmt.Sprintf(\"- **%s** - %s\", tool.Name, tool.Annotations.Title))\n\n\t// Parameters\n\tschema := tool.InputSchema\n\tif len(schema.Properties) > 0 {\n\t\t// Get parameter names and sort them for deterministic order\n\t\tvar paramNames []string\n\t\tfor propName := range schema.Properties {\n\t\t\tparamNames = append(paramNames, propName)\n\t\t}\n\t\tsort.Strings(paramNames)\n\n\t\tfor _, propName := range paramNames {\n\t\t\tprop := schema.Properties[propName]\n\t\t\trequired := contains(schema.Required, propName)\n\t\t\trequiredStr := \"optional\"\n\t\t\tif required {\n\t\t\t\trequiredStr = \"required\"\n\t\t\t}\n\n\t\t\t// Get the type and description\n\t\t\ttypeStr := \"unknown\"\n\t\t\tdescription := \"\"\n\n\t\t\tif propMap, ok := prop.(map[string]interface{}); ok {\n\t\t\t\tif typeVal, ok := propMap[\"type\"].(string); ok {\n\t\t\t\t\tif typeVal == \"array\" {\n\t\t\t\t\t\tif items, ok := propMap[\"items\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif itemType, ok := items[\"type\"].(string); ok {\n\t\t\t\t\t\t\t\ttypeStr = itemType + \"[]\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttypeStr = \"array\"\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttypeStr = typeVal\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif desc, ok := propMap[\"description\"].(string); ok {\n\t\t\t\t\tdescription = desc\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tparamLine := fmt.Sprintf(\" - `%s`: %s (%s, %s)\", propName, description, typeStr, requiredStr)\n\t\t\tlines = append(lines, paramLine)\n\t\t}\n\t} else {\n\t\tlines = append(lines, \" - No parameters required\")\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc contains(slice []string, item string) bool {\n\tfor _, s := range slice {\n\t\tif s == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc replaceSection(content, startMarker, endMarker, newContent string) string {\n\tstartPattern := fmt.Sprintf(`<!-- %s -->`, regexp.QuoteMeta(startMarker))\n\tendPattern := fmt.Sprintf(`<!-- %s -->`, regexp.QuoteMeta(endMarker))\n\n\tre := regexp.MustCompile(fmt.Sprintf(`(?s)%s.*?%s`, startPattern, endPattern))\n\n\treplacement := fmt.Sprintf(\"<!-- %s -->\\n%s\\n<!-- %s -->\", startMarker, newContent, endMarker)\n\n\treturn re.ReplaceAllString(content, replacement)\n}\n\nfunc generateRemoteToolsetsDoc() string {\n\tvar buf strings.Builder\n\n\t// Create translation helper\n\tt, _ := translations.TranslationHelper()\n\n\t// Create toolset group with mock clients\n\ttsg := github.DefaultToolsetGroup(false, mockGetClient, mockGetGQLClient, mockGetRawClient, t)\n\n\t// Generate table header\n\tbuf.WriteString(\"| Name | Description | API URL | 1-Click Install (VS Code) | Read-only Link | 1-Click Read-only Install (VS Code) |\\n\")\n\tbuf.WriteString(\"|----------------|--------------------------------------------------|-------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\\n\")\n\n\t// Get all toolsets\n\ttoolsetNames := make([]string, 0, len(tsg.Toolsets))\n\tfor name := range tsg.Toolsets {\n\t\tif name != \"context\" && name != \"dynamic\" { // Skip context and dynamic toolsets as they're handled separately\n\t\t\ttoolsetNames = append(toolsetNames, name)\n\t\t}\n\t}\n\tsort.Strings(toolsetNames)\n\n\t// Add \"all\" toolset first (special case)\n\tbuf.WriteString(\"| all | All available GitHub MCP tools | https://api.githubcopilot.com/mcp/ | [Install](https://insiders.vscode.dev/redirect/mcp/install?name=github&config=%7B%22type%22%3A%20%22http%22%2C%22url%22%3A%20%22https%3A%2F%2Fapi.githubcopilot.com%2Fmcp%2F%22%7D) | [read-only](https://api.githubcopilot.com/mcp/readonly) | [Install read-only](https://insiders.vscode.dev/redirect/mcp/install?name=github&config=%7B%22type%22%3A%20%22http%22%2C%22url%22%3A%20%22https%3A%2F%2Fapi.githubcopilot.com%2Fmcp%2Freadonly%22%7D) |\\n\")\n\n\t// Add individual toolsets\n\tfor _, name := range toolsetNames {\n\t\ttoolset := tsg.Toolsets[name]\n\n\t\tformattedName := formatToolsetName(name)\n\t\tdescription := toolset.Description\n\t\tapiURL := fmt.Sprintf(\"https://api.githubcopilot.com/mcp/x/%s\", name)\n\t\treadonlyURL := fmt.Sprintf(\"https://api.githubcopilot.com/mcp/x/%s/readonly\", name)\n\n\t\t// Create install config JSON (URL encoded)\n\t\tinstallConfig := url.QueryEscape(fmt.Sprintf(`{\"type\": \"http\",\"url\": \"%s\"}`, apiURL))\n\t\treadonlyConfig := url.QueryEscape(fmt.Sprintf(`{\"type\": \"http\",\"url\": \"%s\"}`, readonlyURL))\n\n\t\t// Fix URL encoding to use %20 instead of + for spaces\n\t\tinstallConfig = strings.ReplaceAll(installConfig, \"+\", \"%20\")\n\t\treadonlyConfig = strings.ReplaceAll(readonlyConfig, \"+\", \"%20\")\n\n\t\tinstallLink := fmt.Sprintf(\"[Install](https://insiders.vscode.dev/redirect/mcp/install?name=gh-%s&config=%s)\", name, installConfig)\n\t\treadonlyInstallLink := fmt.Sprintf(\"[Install read-only](https://insiders.vscode.dev/redirect/mcp/install?name=gh-%s&config=%s)\", name, readonlyConfig)\n\n\t\tbuf.WriteString(fmt.Sprintf(\"| %-14s | %-48s | %-53s | %-218s | %-110s | %-288s |\\n\",\n\t\t\tformattedName,\n\t\t\tdescription,\n\t\t\tapiURL,\n\t\t\tinstallLink,\n\t\t\tfmt.Sprintf(\"[read-only](%s)\", readonlyURL),\n\t\t\treadonlyInstallLink,\n\t\t))\n\t}\n\n\treturn buf.String()\n}\n"], ["/github-mcp-server/internal/githubv4mock/local_round_tripper.go", "// Ths contents of this file are taken from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/graphql_test.go#L155-L165\n// because they are not exported by the module, and we would like to use them in building the githubv4mock test utility.\n//\n// The original license, copied from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/LICENSE\n//\n// MIT License\n\n// Copyright (c) 2017 Dmitri Shuralyov\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\npackage githubv4mock\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\n// localRoundTripper is an http.RoundTripper that executes HTTP transactions\n// by using handler directly, instead of going over an HTTP connection.\ntype localRoundTripper struct {\n\thandler http.Handler\n}\n\nfunc (l localRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tw := httptest.NewRecorder()\n\tl.handler.ServeHTTP(w, req)\n\treturn w.Result(), nil\n}\n"], ["/github-mcp-server/cmd/github-mcp-server/main.go", "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/github/github-mcp-server/internal/ghmcp\"\n\t\"github.com/github/github-mcp-server/pkg/github\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n\t\"github.com/spf13/viper\"\n)\n\n// These variables are set by the build process using ldflags.\nvar version = \"version\"\nvar commit = \"commit\"\nvar date = \"date\"\n\nvar (\n\trootCmd = &cobra.Command{\n\t\tUse: \"server\",\n\t\tShort: \"GitHub MCP Server\",\n\t\tLong: `A GitHub MCP server that handles various tools and resources.`,\n\t\tVersion: fmt.Sprintf(\"Version: %s\\nCommit: %s\\nBuild Date: %s\", version, commit, date),\n\t}\n\n\tstdioCmd = &cobra.Command{\n\t\tUse: \"stdio\",\n\t\tShort: \"Start stdio server\",\n\t\tLong: `Start a server that communicates via standard input/output streams using JSON-RPC messages.`,\n\t\tRunE: func(_ *cobra.Command, _ []string) error {\n\t\t\ttoken := viper.GetString(\"personal_access_token\")\n\t\t\tif token == \"\" {\n\t\t\t\treturn errors.New(\"GITHUB_PERSONAL_ACCESS_TOKEN not set\")\n\t\t\t}\n\n\t\t\t// If you're wondering why we're not using viper.GetStringSlice(\"toolsets\"),\n\t\t\t// it's because viper doesn't handle comma-separated values correctly for env\n\t\t\t// vars when using GetStringSlice.\n\t\t\t// https://github.com/spf13/viper/issues/380\n\t\t\tvar enabledToolsets []string\n\t\t\tif err := viper.UnmarshalKey(\"toolsets\", &enabledToolsets); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to unmarshal toolsets: %w\", err)\n\t\t\t}\n\n\t\t\tstdioServerConfig := ghmcp.StdioServerConfig{\n\t\t\t\tVersion: version,\n\t\t\t\tHost: viper.GetString(\"host\"),\n\t\t\t\tToken: token,\n\t\t\t\tEnabledToolsets: enabledToolsets,\n\t\t\t\tDynamicToolsets: viper.GetBool(\"dynamic_toolsets\"),\n\t\t\t\tReadOnly: viper.GetBool(\"read-only\"),\n\t\t\t\tExportTranslations: viper.GetBool(\"export-translations\"),\n\t\t\t\tEnableCommandLogging: viper.GetBool(\"enable-command-logging\"),\n\t\t\t\tLogFilePath: viper.GetString(\"log-file\"),\n\t\t\t}\n\t\t\treturn ghmcp.RunStdioServer(stdioServerConfig)\n\t\t},\n\t}\n)\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\trootCmd.SetGlobalNormalizationFunc(wordSepNormalizeFunc)\n\n\trootCmd.SetVersionTemplate(\"{{.Short}}\\n{{.Version}}\\n\")\n\n\t// Add global flags that will be shared by all commands\n\trootCmd.PersistentFlags().StringSlice(\"toolsets\", github.DefaultTools, \"An optional comma separated list of groups of tools to allow, defaults to enabling all\")\n\trootCmd.PersistentFlags().Bool(\"dynamic-toolsets\", false, \"Enable dynamic toolsets\")\n\trootCmd.PersistentFlags().Bool(\"read-only\", false, \"Restrict the server to read-only operations\")\n\trootCmd.PersistentFlags().String(\"log-file\", \"\", \"Path to log file\")\n\trootCmd.PersistentFlags().Bool(\"enable-command-logging\", false, \"When enabled, the server will log all command requests and responses to the log file\")\n\trootCmd.PersistentFlags().Bool(\"export-translations\", false, \"Save translations to a JSON file\")\n\trootCmd.PersistentFlags().String(\"gh-host\", \"\", \"Specify the GitHub hostname (for GitHub Enterprise etc.)\")\n\n\t// Bind flag to viper\n\t_ = viper.BindPFlag(\"toolsets\", rootCmd.PersistentFlags().Lookup(\"toolsets\"))\n\t_ = viper.BindPFlag(\"dynamic_toolsets\", rootCmd.PersistentFlags().Lookup(\"dynamic-toolsets\"))\n\t_ = viper.BindPFlag(\"read-only\", rootCmd.PersistentFlags().Lookup(\"read-only\"))\n\t_ = viper.BindPFlag(\"log-file\", rootCmd.PersistentFlags().Lookup(\"log-file\"))\n\t_ = viper.BindPFlag(\"enable-command-logging\", rootCmd.PersistentFlags().Lookup(\"enable-command-logging\"))\n\t_ = viper.BindPFlag(\"export-translations\", rootCmd.PersistentFlags().Lookup(\"export-translations\"))\n\t_ = viper.BindPFlag(\"host\", rootCmd.PersistentFlags().Lookup(\"gh-host\"))\n\n\t// Add subcommands\n\trootCmd.AddCommand(stdioCmd)\n}\n\nfunc initConfig() {\n\t// Initialize Viper configuration\n\tviper.SetEnvPrefix(\"github\")\n\tviper.AutomaticEnv()\n\n}\n\nfunc main() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc wordSepNormalizeFunc(_ *pflag.FlagSet, name string) pflag.NormalizedName {\n\tfrom := []string{\"_\"}\n\tto := \"-\"\n\tfor _, sep := range from {\n\t\tname = strings.ReplaceAll(name, sep, to)\n\t}\n\treturn pflag.NormalizedName(name)\n}\n"], ["/github-mcp-server/internal/githubv4mock/objects_are_equal_values.go", "// The contents of this file are taken from https://github.com/stretchr/testify/blob/016e2e9c269209287f33ec203f340a9a723fe22c/assert/assertions.go#L166\n// because I do not want to take a dependency on the entire testify module just to use this equality check.\n//\n// There is a modification in objectsAreEqual to check that typed nils are equal, even if their types are different.\n//\n// The original license, copied from https://github.com/stretchr/testify/blob/016e2e9c269209287f33ec203f340a9a723fe22c/LICENSE\n//\n// MIT License\n//\n// Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors.\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\npackage githubv4mock\n\nimport (\n\t\"bytes\"\n\t\"reflect\"\n)\n\nfunc objectsAreEqualValues(expected, actual any) bool {\n\tif objectsAreEqual(expected, actual) {\n\t\treturn true\n\t}\n\n\texpectedValue := reflect.ValueOf(expected)\n\tactualValue := reflect.ValueOf(actual)\n\tif !expectedValue.IsValid() || !actualValue.IsValid() {\n\t\treturn false\n\t}\n\n\texpectedType := expectedValue.Type()\n\tactualType := actualValue.Type()\n\tif !expectedType.ConvertibleTo(actualType) {\n\t\treturn false\n\t}\n\n\tif !isNumericType(expectedType) || !isNumericType(actualType) {\n\t\t// Attempt comparison after type conversion\n\t\treturn reflect.DeepEqual(\n\t\t\texpectedValue.Convert(actualType).Interface(), actual,\n\t\t)\n\t}\n\n\t// If BOTH values are numeric, there are chances of false positives due\n\t// to overflow or underflow. So, we need to make sure to always convert\n\t// the smaller type to a larger type before comparing.\n\tif expectedType.Size() >= actualType.Size() {\n\t\treturn actualValue.Convert(expectedType).Interface() == expected\n\t}\n\n\treturn expectedValue.Convert(actualType).Interface() == actual\n}\n\n// objectsAreEqual determines if two objects are considered equal.\n//\n// This function does no assertion of any kind.\nfunc objectsAreEqual(expected, actual any) bool {\n\t// There is a modification in objectsAreEqual to check that typed nils are equal, even if their types are different.\n\t// This is required because when a nil is provided as a variable, the type is not known.\n\tif isNil(expected) && isNil(actual) {\n\t\treturn true\n\t}\n\n\texp, ok := expected.([]byte)\n\tif !ok {\n\t\treturn reflect.DeepEqual(expected, actual)\n\t}\n\n\tact, ok := actual.([]byte)\n\tif !ok {\n\t\treturn false\n\t}\n\tif exp == nil || act == nil {\n\t\treturn exp == nil && act == nil\n\t}\n\treturn bytes.Equal(exp, act)\n}\n\n// isNumericType returns true if the type is one of:\n// int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64,\n// float32, float64, complex64, complex128\nfunc isNumericType(t reflect.Type) bool {\n\treturn t.Kind() >= reflect.Int && t.Kind() <= reflect.Complex128\n}\n\nfunc isNil(i any) bool {\n\tif i == nil {\n\t\treturn true\n\t}\n\tv := reflect.ValueOf(i)\n\tswitch v.Kind() {\n\tcase reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:\n\t\treturn v.IsNil()\n\tdefault:\n\t\treturn false\n\t}\n}\n"], ["/github-mcp-server/internal/toolsnaps/toolsnaps.go", "// Package toolsnaps provides test utilities for ensuring json schemas for tools\n// have not changed unexpectedly.\npackage toolsnaps\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/josephburnett/jd/v2\"\n)\n\n// Test checks that the JSON schema for a tool has not changed unexpectedly.\n// It compares the marshaled JSON of the provided tool against a stored snapshot file.\n// If the UPDATE_TOOLSNAPS environment variable is set to \"true\", it updates the snapshot file instead.\n// If the snapshot does not exist and not running in CI, it creates the snapshot file.\n// If the snapshot does not exist and running in CI (GITHUB_ACTIONS=\"true\"), it returns an error.\n// If the snapshot exists, it compares the tool's JSON to the snapshot and returns an error if they differ.\n// Returns an error if marshaling, reading, or comparing fails.\nfunc Test(toolName string, tool any) error {\n\ttoolJSON, err := json.MarshalIndent(tool, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal tool %s: %w\", toolName, err)\n\t}\n\n\tsnapPath := fmt.Sprintf(\"__toolsnaps__/%s.snap\", toolName)\n\n\t// If UPDATE_TOOLSNAPS is set, then we write the tool JSON to the snapshot file and exit\n\tif os.Getenv(\"UPDATE_TOOLSNAPS\") == \"true\" {\n\t\treturn writeSnap(snapPath, toolJSON)\n\t}\n\n\tsnapJSON, err := os.ReadFile(snapPath) //nolint:gosec // filepaths are controlled by the test suite, so this is safe.\n\t// If the snapshot file does not exist, this must be the first time this test is run.\n\t// We write the tool JSON to the snapshot file and exit.\n\tif os.IsNotExist(err) {\n\t\t// If we're running in CI, we will error if there is not snapshot because it's important that snapshots\n\t\t// are committed alongside the tests, rather than just being constructed and not committed during a CI run.\n\t\tif os.Getenv(\"GITHUB_ACTIONS\") == \"true\" {\n\t\t\treturn fmt.Errorf(\"tool snapshot does not exist for %s. Please run the tests with UPDATE_TOOLSNAPS=true to create it\", toolName)\n\t\t}\n\n\t\treturn writeSnap(snapPath, toolJSON)\n\t}\n\n\t// Otherwise we will compare the tool JSON to the snapshot JSON\n\ttoolNode, err := jd.ReadJsonString(string(toolJSON))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse tool JSON for %s: %w\", toolName, err)\n\t}\n\n\tsnapNode, err := jd.ReadJsonString(string(snapJSON))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse snapshot JSON for %s: %w\", toolName, err)\n\t}\n\n\t// jd.Set allows arrays to be compared without order sensitivity,\n\t// which is useful because we don't really care about this when exposing tool schemas.\n\tdiff := toolNode.Diff(snapNode, jd.SET).Render()\n\tif diff != \"\" {\n\t\t// If there is a difference, we return an error with the diff\n\t\treturn fmt.Errorf(\"tool schema for %s has changed unexpectedly:\\n%s\\nrun with `UPDATE_TOOLSNAPS=true` if this is expected\", toolName, diff)\n\t}\n\n\treturn nil\n}\n\nfunc writeSnap(snapPath string, contents []byte) error {\n\t// Ensure the directory exists\n\tif err := os.MkdirAll(filepath.Dir(snapPath), 0700); err != nil {\n\t\treturn fmt.Errorf(\"failed to create snapshot directory: %w\", err)\n\t}\n\n\t// Write the snapshot file\n\tif err := os.WriteFile(snapPath, contents, 0600); err != nil {\n\t\treturn fmt.Errorf(\"failed to write snapshot file: %w\", err)\n\t}\n\n\treturn nil\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:05:36", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Construct a configuration object that pairs a specific GraphQL operation request with corresponding input parameters and predefined response data for testing purposes."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\n\tif ok {\n\t\tif variables == nil {\n\t\t\tvariables = map[string]any{\"input\": input}\n\t\t} else {\n\t\t\tvariables[\"input\"] = input\n\t\t}\n\n\t\tm, _ := githubv4InputStructToMap(input)\n\t\tvariables[\"input\"] = m\n\t}\n\n\treturn Matcher{\n\t\tRequest: mutationString,\n\t\tVariables: variables,\n\t\tResponse: response,\n\t}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-07-05"}, "editdistance_info": {"edit_distance": 25.2747, "calculate_time": "2025-08-20 21:07:05", "true_code_clean": "return Matcher{\n\t\tRequest: mutationString,\n\t\tVariables: variables,\n\t\tResponse: response,\n\t}", "predict_code_clean": "if ok {\n\t\tif variables == nil {\n\t\t\tvariables = map[string]any{\"input\": input}\n\t\t} else {\n\t\t\tvariables[\"input\"] = input\n\t\t}\n\t\tm, _ := githubv4InputStructToMap(input)\n\t\tvariables[\"input\"] = m\n\t}\n\treturn Matcher{\n\t\tRequest: mutationString,\n\t\tVariables: variables,\n\t\tResponse: response,\n\t}"}} | |