|
| 1 | +// Package mcp implements the `mcp` command for osv-scanner. |
| 2 | +package mcp |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "net/http" |
| 12 | + |
| 13 | + "github.com/google/osv-scanner/v2/internal/cmdlogger" |
| 14 | + "github.com/google/osv-scanner/v2/internal/output" |
| 15 | + "github.com/google/osv-scanner/v2/internal/version" |
| 16 | + "github.com/google/osv-scanner/v2/pkg/osvscanner" |
| 17 | + "github.com/jedib0t/go-pretty/v6/text" |
| 18 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 19 | + "github.com/ossf/osv-schema/bindings/go/osvschema" |
| 20 | + "github.com/urfave/cli/v3" |
| 21 | + "osv.dev/bindings/go/osvdev" |
| 22 | +) |
| 23 | + |
| 24 | +var vulnCacheMap = map[string]*osvschema.Vulnerability{} |
| 25 | + |
| 26 | +func Command(_, _ io.Writer) *cli.Command { |
| 27 | + return &cli.Command{ |
| 28 | + Name: "experimental-mcp", |
| 29 | + Usage: "Run osv-scanner as an MCP service (experimental)", |
| 30 | + Description: "Run osv-scanner as an MCP service, speaking the MCP protocol over stdin/stdout.", |
| 31 | + Flags: []cli.Flag{ |
| 32 | + &cli.StringFlag{ |
| 33 | + Name: "sse", |
| 34 | + DefaultText: "localhost:8080", |
| 35 | + Value: "localhost:8080", |
| 36 | + Usage: "The listening address for the SSE server, e.g. localhost:8080", |
| 37 | + }, |
| 38 | + }, |
| 39 | + Action: action, |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +type ScanVulnerableDependenciesInput struct { |
| 44 | + Paths []string `json:"paths" jsonschema:"A list of absolute or relative path to a file or directory to scan.,required"` |
| 45 | + IgnoreGlobPatterns []string `json:"ignore_glob_patterns" jsonschema:"A list of glob patterns to ignore when scanning."` |
| 46 | + Recursive bool `json:"recursive" jsonschema:"Scans directory recursively"` |
| 47 | +} |
| 48 | + |
| 49 | +type GetVulnerabilityDetailsInput struct { |
| 50 | + VulnID string `json:"vuln_id" jsonschema:"The OSV vulnerability ID to retrieve details for.,required"` |
| 51 | +} |
| 52 | + |
| 53 | +func action(ctx context.Context, cmd *cli.Command) error { |
| 54 | + s := mcp.NewServer(&mcp.Implementation{ |
| 55 | + Name: "OSV-Scanner", Version: version.OSVVersion, |
| 56 | + }, nil) |
| 57 | + |
| 58 | + mcp.AddTool(s, &mcp.Tool{ |
| 59 | + Name: "scan_vulnerable_dependencies", |
| 60 | + Description: "Scans a source directory for vulnerable dependencies." + |
| 61 | + " Walks the given directory and uses osv.dev to query for vulnerabilities matching the found dependencies." + |
| 62 | + " Use this tool to check that the user's project is not depending on known vulnerable code.", |
| 63 | + }, handleScan) |
| 64 | + |
| 65 | + // TODO(another-rex): Ideally this would be a template resource, but gemini-cli does not support those yet. |
| 66 | + mcp.AddTool(s, &mcp.Tool{ |
| 67 | + Name: "get_vulnerability_details", |
| 68 | + Description: "Retrieves the full JSON details for a given vulnerability ID.", |
| 69 | + }, handleVulnIDRetrieval) |
| 70 | + |
| 71 | + s.AddPrompt(&mcp.Prompt{ |
| 72 | + Name: "scan_deps", |
| 73 | + Description: "Scans your project dependencies for known vulnerabilities.", |
| 74 | + }, handleCodeReview) |
| 75 | + |
| 76 | + if cmd.IsSet("sse") { |
| 77 | + sseAddr := cmd.String("sse") |
| 78 | + cmdlogger.Infof("Starting SSE server on %s", sseAddr) |
| 79 | + handler := mcp.NewSSEHandler(func(_ *http.Request) *mcp.Server { |
| 80 | + return s |
| 81 | + }, nil) |
| 82 | + //nolint:gosec // Having no timeouts is unlikely to cause problems as this is meant to be run locally. |
| 83 | + if err := http.ListenAndServe(sseAddr, handler); err != nil { |
| 84 | + cmdlogger.Errorf("mcp error: %s", err) |
| 85 | + return err |
| 86 | + } |
| 87 | + } else { |
| 88 | + cmdlogger.SendEverythingToStderr() |
| 89 | + cmdlogger.Infof("Starting MCP server on stdio") |
| 90 | + if err := s.Run(ctx, &mcp.StdioTransport{}); err != nil { |
| 91 | + cmdlogger.Errorf("mcp error: %s", err) |
| 92 | + return err |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + return nil |
| 97 | +} |
| 98 | + |
| 99 | +func handleScan(_ context.Context, _ *mcp.CallToolRequest, input *ScanVulnerableDependenciesInput) (*mcp.CallToolResult, any, error) { |
| 100 | + // Security: validate path |
| 101 | + // if !isValidPath(path) { |
| 102 | + // return mcp.NewToolResultError(fmt.Sprintf("invalid path: %s", path)), nil |
| 103 | + //} |
| 104 | + |
| 105 | + statsCollector := fileOpenedLogger{} |
| 106 | + |
| 107 | + action := osvscanner.ScannerActions{ |
| 108 | + DirectoryPaths: input.Paths, |
| 109 | + ScanLicensesSummary: false, |
| 110 | + ExperimentalScannerActions: osvscanner.ExperimentalScannerActions{ |
| 111 | + StatsCollector: &statsCollector, |
| 112 | + }, |
| 113 | + CallAnalysisStates: map[string]bool{ |
| 114 | + "go": true, |
| 115 | + }, |
| 116 | + Recursive: input.Recursive, |
| 117 | + } |
| 118 | + |
| 119 | + //nolint:contextcheck // passing the context in would be a breaking change |
| 120 | + scanResults, err := osvscanner.DoScan(action) |
| 121 | + if err != nil && !errors.Is(err, osvscanner.ErrVulnerabilitiesFound) { |
| 122 | + return nil, nil, fmt.Errorf("failed to run scanner: %w", err) |
| 123 | + } |
| 124 | + |
| 125 | + for _, vuln := range scanResults.Flatten() { |
| 126 | + vulnCacheMap[vuln.Vulnerability.ID] = &vuln.Vulnerability |
| 127 | + } |
| 128 | + |
| 129 | + if err == nil { |
| 130 | + return &mcp.CallToolResult{ |
| 131 | + Content: []mcp.Content{ |
| 132 | + &mcp.TextContent{Text: "No issues found"}, |
| 133 | + }, |
| 134 | + }, nil, nil |
| 135 | + } |
| 136 | + |
| 137 | + buf := strings.Builder{} |
| 138 | + |
| 139 | + for _, s := range statsCollector.collectedLines { |
| 140 | + buf.WriteString(s + "\n") |
| 141 | + } |
| 142 | + |
| 143 | + text.DisableColors() |
| 144 | + output.PrintVerticalResults(&scanResults, &buf, false) |
| 145 | + |
| 146 | + return &mcp.CallToolResult{ |
| 147 | + Content: []mcp.Content{ |
| 148 | + &mcp.TextContent{Text: buf.String()}, |
| 149 | + }, |
| 150 | + }, nil, nil |
| 151 | +} |
| 152 | + |
| 153 | +func handleVulnIDRetrieval(ctx context.Context, _ *mcp.CallToolRequest, input *GetVulnerabilityDetailsInput) (*mcp.CallToolResult, *osvschema.Vulnerability, error) { |
| 154 | + vuln, found := vulnCacheMap[input.VulnID] |
| 155 | + if !found { |
| 156 | + var err error |
| 157 | + vuln, err = osvdev.DefaultClient().GetVulnByID(ctx, input.VulnID) |
| 158 | + if err != nil { |
| 159 | + return nil, nil, fmt.Errorf("vulnerability with ID %s not found: %w", input.VulnID, err) |
| 160 | + } |
| 161 | + |
| 162 | + vulnCacheMap[input.VulnID] = vuln |
| 163 | + } |
| 164 | + |
| 165 | + return &mcp.CallToolResult{}, vuln, nil |
| 166 | +} |
| 167 | + |
| 168 | +func handleCodeReview(_ context.Context, _ *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) { |
| 169 | + return &mcp.GetPromptResult{ |
| 170 | + Description: "Dependency vulnerability analysis", |
| 171 | + Messages: []*mcp.PromptMessage{ |
| 172 | + { |
| 173 | + Role: "assistant", |
| 174 | + Content: &mcp.TextContent{ |
| 175 | + Text: ` |
| 176 | +
|
| 177 | +You are a highly skilled senior security analyst. |
| 178 | +Your primary task is to conduct a security audit of the vulnerabilities in the dependencies of this project. |
| 179 | +Utilizing your skillset, you must operate by strictly following the operating principles defined in your context. |
| 180 | +
|
| 181 | +**Step 1: Perform initial scan** |
| 182 | +
|
| 183 | +Use the scan_vulnerable_dependencies with recursive on the project, always use the absolute path. |
| 184 | +This will return a report of all the relevant lockfiles and all vulnerable dependencies in those files. |
| 185 | +
|
| 186 | +**Step 2: Analyse the report** |
| 187 | +
|
| 188 | +Go through the report and determine the relevant project lockfiles (ignoring lockfiles in test directories), |
| 189 | +and prioritise which vulnerability to fix based on the description and severity. |
| 190 | +If more information is needed about a vulnerability, use get_vulnerability_details. |
| 191 | +
|
| 192 | +**Step 3: Prioritisation** |
| 193 | +
|
| 194 | +Give advice on which vulnerabilities to prioritise fixing, and general advice on how to go about fixing |
| 195 | +them by updating. Don't try to automatically update for the user without input. |
| 196 | +`, |
| 197 | + }, |
| 198 | + }, |
| 199 | + }, |
| 200 | + }, nil |
| 201 | +} |
0 commit comments