|
| 1 | +// Package mcp implements the `mcp` command for osv-scanner. |
| 2 | +package mcp |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + _ "embed" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "strings" |
| 11 | + "sync" |
| 12 | + "time" |
| 13 | + |
| 14 | + "net/http" |
| 15 | + |
| 16 | + "github.com/google/osv-scanner/v2/internal/cmdlogger" |
| 17 | + "github.com/google/osv-scanner/v2/internal/output" |
| 18 | + "github.com/google/osv-scanner/v2/internal/version" |
| 19 | + "github.com/google/osv-scanner/v2/pkg/osvscanner" |
| 20 | + "github.com/jedib0t/go-pretty/v6/text" |
| 21 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 22 | + "github.com/ossf/osv-schema/bindings/go/osvschema" |
| 23 | + "github.com/urfave/cli/v3" |
| 24 | + "osv.dev/bindings/go/osvdev" |
| 25 | +) |
| 26 | + |
| 27 | +// vulnCacheMap is a cache of vulnerability details that have been retrieved from the OSV API during normal scanning. |
| 28 | +// This avoids unnecessary double queries to the osv.dev API. |
| 29 | +// vulnCacheMap: map[string]*osvschema.Vulnerability |
| 30 | +var vulnCacheMap = sync.Map{} |
| 31 | + |
| 32 | +// Command is the entry point for the `mcp` subcommand. |
| 33 | +func Command(_, _ io.Writer) *cli.Command { |
| 34 | + return &cli.Command{ |
| 35 | + Name: "experimental-mcp", |
| 36 | + Usage: "Run osv-scanner as an MCP service (experimental)", |
| 37 | + Description: "Run osv-scanner as an MCP service, speaking the MCP protocol over stdin/stdout.", |
| 38 | + Flags: []cli.Flag{ |
| 39 | + &cli.StringFlag{ |
| 40 | + Name: "sse", |
| 41 | + DefaultText: "localhost:8080", |
| 42 | + Value: "localhost:8080", |
| 43 | + Usage: "The listening address for the SSE server, e.g. localhost:8080", |
| 44 | + }, |
| 45 | + }, |
| 46 | + Action: action, |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// scanVulnerableDependenciesInput is the input for the scan_vulnerable_dependencies tool. |
| 51 | +type scanVulnerableDependenciesInput struct { |
| 52 | + Paths []string `json:"paths" jsonschema:"A list of absolute or relative path to a file or directory to scan."` |
| 53 | + IgnoreGlobPatterns []string `json:"ignore_glob_patterns" jsonschema:"A list of glob patterns to ignore when scanning."` |
| 54 | + Recursive bool `json:"recursive" jsonschema:"Scans directory recursively"` |
| 55 | +} |
| 56 | + |
| 57 | +func action(ctx context.Context, cmd *cli.Command) error { |
| 58 | + s := mcp.NewServer(&mcp.Implementation{ |
| 59 | + Name: "OSV-Scanner", Version: version.OSVVersion, |
| 60 | + }, nil) |
| 61 | + |
| 62 | + mcp.AddTool(s, &mcp.Tool{ |
| 63 | + Name: "scan_vulnerable_dependencies", |
| 64 | + Description: "Scans a source directory for vulnerable dependencies." + |
| 65 | + " Walks the given directory and uses osv.dev to query for vulnerabilities matching the found dependencies." + |
| 66 | + " Use this tool to check that the user's project is not depending on known vulnerable code.", |
| 67 | + }, handleScan) |
| 68 | + |
| 69 | + // TODO(another-rex): Ideally both of the following tools would be resources, but gemini-cli does not support those yet. |
| 70 | + mcp.AddTool(s, &mcp.Tool{ |
| 71 | + Name: "get_vulnerability_details", |
| 72 | + Description: "Retrieves the full JSON details for a given vulnerability ID.", |
| 73 | + }, handleVulnIDRetrieval) |
| 74 | + |
| 75 | + mcp.AddTool(s, &mcp.Tool{ |
| 76 | + Name: "ignore_vulnerability", |
| 77 | + Description: "Provides instructions for writing a config file to exclude vulnerabilities from the scan report.", |
| 78 | + }, handleIgnoreVulnerability) |
| 79 | + |
| 80 | + s.AddPrompt(&mcp.Prompt{ |
| 81 | + Name: "scan_deps", |
| 82 | + Description: "Scans your project dependencies for known vulnerabilities.", |
| 83 | + }, handleScanDepsPrompt) |
| 84 | + |
| 85 | + // Provide two options, sse on a network port, or stdio. |
| 86 | + if cmd.IsSet("sse") { |
| 87 | + sseAddr := cmd.String("sse") |
| 88 | + cmdlogger.Infof("Starting SSE server on %s", sseAddr) |
| 89 | + handler := mcp.NewSSEHandler(func(_ *http.Request) *mcp.Server { |
| 90 | + return s |
| 91 | + }, nil) |
| 92 | + srv := &http.Server{ |
| 93 | + Addr: sseAddr, |
| 94 | + Handler: handler, |
| 95 | + ReadTimeout: 30 * time.Second, |
| 96 | + WriteTimeout: 30 * time.Second, |
| 97 | + IdleTimeout: 120 * time.Second, |
| 98 | + } |
| 99 | + if err := srv.ListenAndServe(); err != nil { |
| 100 | + cmdlogger.Errorf("mcp error: %s", err) |
| 101 | + return err |
| 102 | + } |
| 103 | + } else { |
| 104 | + cmdlogger.SendEverythingToStderr() |
| 105 | + cmdlogger.Infof("Starting MCP server on stdio") |
| 106 | + if err := s.Run(ctx, &mcp.StdioTransport{}); err != nil { |
| 107 | + cmdlogger.Errorf("mcp error: %s", err) |
| 108 | + return err |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + return nil |
| 113 | +} |
| 114 | + |
| 115 | +func handleScan(_ context.Context, _ *mcp.CallToolRequest, input *scanVulnerableDependenciesInput) (*mcp.CallToolResult, any, error) { |
| 116 | + statsCollector := fileOpenedLogger{} |
| 117 | + |
| 118 | + action := osvscanner.ScannerActions{ |
| 119 | + DirectoryPaths: input.Paths, |
| 120 | + ScanLicensesSummary: false, |
| 121 | + ExperimentalScannerActions: osvscanner.ExperimentalScannerActions{ |
| 122 | + StatsCollector: &statsCollector, |
| 123 | + }, |
| 124 | + CallAnalysisStates: map[string]bool{ |
| 125 | + "go": true, |
| 126 | + }, |
| 127 | + Recursive: input.Recursive, |
| 128 | + } |
| 129 | + |
| 130 | + //nolint:contextcheck // passing the context in would be a breaking change |
| 131 | + scanResults, err := osvscanner.DoScan(action) |
| 132 | + if err != nil && !errors.Is(err, osvscanner.ErrVulnerabilitiesFound) { |
| 133 | + return nil, nil, fmt.Errorf("failed to run scanner: %w", err) |
| 134 | + } |
| 135 | + |
| 136 | + for _, vuln := range scanResults.Flatten() { |
| 137 | + vulnCacheMap.Store(vuln.Vulnerability.ID, &vuln.Vulnerability) |
| 138 | + } |
| 139 | + |
| 140 | + if err == nil { |
| 141 | + return &mcp.CallToolResult{ |
| 142 | + Content: []mcp.Content{ |
| 143 | + &mcp.TextContent{Text: "No issues found"}, |
| 144 | + }, |
| 145 | + }, nil, nil |
| 146 | + } |
| 147 | + |
| 148 | + buf := strings.Builder{} |
| 149 | + |
| 150 | + for _, s := range statsCollector.collectedLines { |
| 151 | + buf.WriteString(s + "\n") |
| 152 | + } |
| 153 | + |
| 154 | + text.DisableColors() |
| 155 | + output.PrintVerticalResults(&scanResults, &buf, false) |
| 156 | + |
| 157 | + return &mcp.CallToolResult{ |
| 158 | + Content: []mcp.Content{ |
| 159 | + &mcp.TextContent{Text: buf.String()}, |
| 160 | + }, |
| 161 | + }, nil, nil |
| 162 | +} |
| 163 | + |
| 164 | +// getVulnerabilityDetailsInput is the input for the get_vulnerability_details tool. |
| 165 | +type getVulnerabilityDetailsInput struct { |
| 166 | + VulnID string `json:"vuln_id" jsonschema:"The OSV vulnerability ID to retrieve details for."` |
| 167 | +} |
| 168 | + |
| 169 | +func handleVulnIDRetrieval(ctx context.Context, _ *mcp.CallToolRequest, input *getVulnerabilityDetailsInput) (*mcp.CallToolResult, *osvschema.Vulnerability, error) { |
| 170 | + vulnAny, found := vulnCacheMap.Load(input.VulnID) |
| 171 | + vuln := vulnAny.(*osvschema.Vulnerability) |
| 172 | + if !found { |
| 173 | + var err error |
| 174 | + vuln, err = osvdev.DefaultClient().GetVulnByID(ctx, input.VulnID) |
| 175 | + if err != nil { |
| 176 | + return nil, nil, fmt.Errorf("vulnerability with ID %s not found: %w", input.VulnID, err) |
| 177 | + } |
| 178 | + |
| 179 | + vulnCacheMap.Store(input.VulnID, vuln) |
| 180 | + } |
| 181 | + |
| 182 | + return &mcp.CallToolResult{}, vuln, nil |
| 183 | +} |
| 184 | + |
| 185 | +// ignoreVulnerabilityInput is a placeholder to enable the tool call, |
| 186 | +// as it seems like go-sdk mcp does not support a tool call with no arguments. |
| 187 | +type ignoreVulnerabilityInput struct { |
| 188 | + // Extra field is needed as a placeholder to prevent the llm from erroring when calling the tool |
| 189 | + Verbose bool `json:"verbose" jsonschema:"ignore this parameter"` |
| 190 | +} |
| 191 | + |
| 192 | +//go:embed configuration-instructions.md |
| 193 | +var configInstructions string |
| 194 | + |
| 195 | +// handleIgnoreVulnerability does not perform any actual actions, but instead provides the instructions of how |
| 196 | +// to write an ignore file to the LLM using this tool, so that it can correctly write the ignore file. |
| 197 | +func handleIgnoreVulnerability(_ context.Context, _ *mcp.CallToolRequest, _ *ignoreVulnerabilityInput) (*mcp.CallToolResult, any, error) { |
| 198 | + return &mcp.CallToolResult{ |
| 199 | + Content: []mcp.Content{ |
| 200 | + &mcp.TextContent{Text: configInstructions}, |
| 201 | + }, |
| 202 | + }, nil, nil |
| 203 | +} |
| 204 | + |
| 205 | +// scanDepsPrompt is the prompt that is sent to the AI model when the scan_deps prompt is requested. |
| 206 | +// |
| 207 | +//go:embed scan-deps-prompt.md |
| 208 | +var scanDepsPrompt string |
| 209 | + |
| 210 | +func handleScanDepsPrompt(_ context.Context, _ *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) { |
| 211 | + return &mcp.GetPromptResult{ |
| 212 | + Description: "Dependency vulnerability analysis", |
| 213 | + Messages: []*mcp.PromptMessage{ |
| 214 | + { |
| 215 | + Role: "assistant", |
| 216 | + Content: &mcp.TextContent{ |
| 217 | + Text: scanDepsPrompt, |
| 218 | + }, |
| 219 | + }, |
| 220 | + }, |
| 221 | + }, nil |
| 222 | +} |
0 commit comments