Skip to content
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

DuckDuckGo + Filesystem Management #9

Merged
9 commits merged into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
901 changes: 899 additions & 2 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
"publish-all": "npm publish --workspaces --access public && npm publish --access public"
},
"dependencies": {
"@modelcontextprotocol/server-duckduckgo": "*",
"@modelcontextprotocol/server-everything": "*",
"@modelcontextprotocol/server-filesystem": "*",
"@modelcontextprotocol/server-gdrive": "*",
"@modelcontextprotocol/server-postgres": "*",
"@modelcontextprotocol/server-puppeteer": "*",
Expand Down
37 changes: 37 additions & 0 deletions src/duckduckgo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# DuckDuckGo MCP Server

MCP server providing search functionality via DuckDuckGo's HTML interface.

## Components

### Resources
Single resource endpoint for search interface:
```duckduckgo://search```

### Tools
- **duckduckgo_search**
- Performs a search using DuckDuckGo and returns the top search results
- Inputs:
- `query` (string, required): The search query to look up
- `numResults` (number, optional): Number of results to return (default: 10)
- Returns titles, snippets, and URLs of the search results

## Usage Example
```javascript
// Example tool call
{
"name": "duckduckgo_search",
"arguments": {
"query": "your search query",
"numResults": 10
}
}

// Example response format:
{
"content": [{
"type": "text",
"text": "Title: Result Title\nSnippet: Result description...\nURL: https://example.com\n\nTitle: Another Result\n..."
}]
}
```
176 changes: 176 additions & 0 deletions src/duckduckgo/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
#!/usr/bin/env node

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
import fetch from "node-fetch";
import { JSDOM } from "jsdom";

const SEARCH_TOOL: Tool = {
name: "duckduckgo_search",
description:
"Performs a search using DuckDuckGo and returns the top search results. " +
"Returns titles, snippets, and URLs of the search results. " +
"Use this tool to search for current information on the internet.",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "The search query to look up",
},
numResults: {
type: "number",
description: "Number of results to return (default: 10)",
default: 10,
},
},
required: ["query"],
},
};

const server = new Server(
{
name: "example-servers/duckduckgo",
version: "0.1.0",
},
{
capabilities: {
tools: {},
resources: {},
},
},
);

server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: [
{
uri: "duckduckgo://search",
mimeType: "text/plain",
name: "DuckDuckGo Search Results",
},
],
}));

server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
if (request.params.uri.toString() === "duckduckgo://search") {
return {
contents: [
{
uri: "duckduckgo://search",
mimeType: "text/plain",
text: "DuckDuckGo search interface",
},
],
};
}
throw new Error("Resource not found");
});

server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [SEARCH_TOOL],
}));

async function performSearch(query: string, numResults: number = 10) {
const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`;
const headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use a User-Agent that identifies this code specifically, so DDG could track where it's coming from if needed?

};

const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const html = await response.text();
const dom = new JSDOM(html);
const document = dom.window.document;

const results = [];
const resultElements = document.querySelectorAll(".result");

for (let i = 0; i < Math.min(numResults, resultElements.length); i++) {
const result = resultElements[i];
const titleElem = result.querySelector(".result__title");
const snippetElem = result.querySelector(".result__snippet");
const urlElem = result.querySelector(".result__url");

if (titleElem && snippetElem) {
results.push({
title: titleElem.textContent?.trim() || "",
snippet: snippetElem.textContent?.trim() || "",
url: urlElem?.getAttribute("href") || "",
});
}
}

return results;
}

server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "duckduckgo_search") {
try {
const { query, numResults = 10 } = request.params.arguments as {
query: string;
numResults?: number;
};

const results = await performSearch(query, numResults);

const formattedResults = results
.map(
(result) =>
`Title: ${result.title}\nSnippet: ${result.snippet}\nURL: ${result.url}\n`,
)
.join("\n");

return {
content: [
{
type: "text",
text: formattedResults || "No results found.",
},
],
isError: false,
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error performing search: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
};
}
}

return {
content: [
{
type: "text",
text: `Unknown tool: ${request.params.name}`,
},
],
isError: true,
};
});

async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("DuckDuckGo MCP Server running on stdio");
}

runServer().catch((error) => {
console.error("Fatal error running server:", error);
process.exit(1);
});
32 changes: 32 additions & 0 deletions src/duckduckgo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "@modelcontextprotocol/server-duckduckgo",
"version": "0.1.0",
"description": "MCP server for DuckDuckGo search",
"license": "MIT",
"author": "Anthropic, PBC (https://anthropic.com)",
"homepage": "https://modelcontextprotocol.io",
"bugs": "https://github.com/modelcontextprotocol/servers/issues",
"type": "module",
"bin": {
"mcp-server-duckduckgo": "dist/index.js"
},
"files": [
"dist"
],
"scripts": {
"build": "tsc && shx chmod +x dist/*.js",
"prepare": "npm run build",
"watch": "tsc --watch"
},
"dependencies": {
"@modelcontextprotocol/sdk": "0.5.0",
"jsdom": "^24.1.3",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@types/jsdom": "^21.1.6",
"@types/node": "^20.10.0",
"shx": "^0.3.4",
"typescript": "^5.6.2"
}
}
10 changes: 10 additions & 0 deletions src/duckduckgo/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "."
},
"include": [
"./**/*.ts"
]
}
76 changes: 76 additions & 0 deletions src/filesystem/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Filesystem MCP Server

Node.js server implementing Model Context Protocol (MCP) for filesystem operations.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the idea of this server, but it's a bit of a security nightmare right now. I think we should lock it down so that it only makes available specific directories on disk (e.g., passed as CLI arguments), and then we have to be really careful with all of our fs operations checks to ensure that they're happening entirely within that directory (accounting for symlinks and other weirdness too).

Does that sound reasonable? I can help out here if it'd be useful.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think that makes sense - Pietro & I chatted a bit about this last night as well.

@Skirano do you have thoughts on this? If you agree, would you mind updating this (or working with Justin) such that it only works for specific directories that get passed in? Sorry for all the back and forth here!

Re: duckduckgo - understand your concern. I'll defer to the slack thread's outcome.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I can add that!


## Features

- Read/write files
- Create/list/delete directories
- Move files/directories
- Search files
- Get file metadata

## API

### Resources

- `file://system`: File system operations interface

### Tools

- **read_file**
- Read complete contents of a file
- Input: `path` (string)
- Reads complete file contents with UTF-8 encoding

- **read_multiple_files**
- Read multiple files simultaneously
- Input: `paths` (string[])
- Failed reads won't stop the entire operation

- **write_file**
- Create new file or overwrite existing
- Inputs:
- `path` (string): File location
- `content` (string): File content

- **create_directory**
- Create new directory or ensure it exists
- Input: `path` (string)
- Creates parent directories if needed
- Succeeds silently if directory exists

- **list_directory**
- List directory contents with [FILE] or [DIR] prefixes
- Input: `path` (string)

- **move_file**
- Move or rename files and directories
- Inputs:
- `source` (string)
- `destination` (string)
- Fails if destination exists

- **search_files**
- Recursively search for files/directories
- Inputs:
- `path` (string): Starting directory
- `pattern` (string): Search pattern
- Case-insensitive matching
- Returns full paths to matches

- **get_file_info**
- Get detailed file/directory metadata
- Input: `path` (string)
- Returns:
- Size
- Creation time
- Modified time
- Access time
- Type (file/directory)
- Permissions

## Notes

- Exercise caution with `write_file`, since it can overwrite an existing file
- File paths can be absolute or relative
Loading