@oevortex/ddg_search 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +194 -0
- package/README.md +224 -0
- package/bin/cli.js +144 -0
- package/package.json +28 -0
- package/src/index.js +78 -0
- package/src/tools/fetchUrlTool.js +118 -0
- package/src/tools/metadataTool.js +58 -0
- package/src/tools/searchTool.js +64 -0
- package/src/utils/search.js +401 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting the License. You accept and agree to be bound by the
|
|
166
|
+
terms of this License by copying, modifying, or distributing the
|
|
167
|
+
Work (or any work based on the Work).
|
|
168
|
+
|
|
169
|
+
END OF TERMS AND CONDITIONS
|
|
170
|
+
|
|
171
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
172
|
+
|
|
173
|
+
To apply the Apache License to your work, attach the following
|
|
174
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
175
|
+
replaced with your own identifying information. (Don't include
|
|
176
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
177
|
+
comment syntax for the file format. We also recommend that a
|
|
178
|
+
file or class name and description of purpose be included on the
|
|
179
|
+
same "printed page" as the copyright notice for easier
|
|
180
|
+
identification within third-party archives.
|
|
181
|
+
|
|
182
|
+
Copyright [yyyy] [name of copyright owner]
|
|
183
|
+
|
|
184
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
185
|
+
you may not use this file except in compliance with the License.
|
|
186
|
+
You may obtain a copy of the License at
|
|
187
|
+
|
|
188
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
189
|
+
|
|
190
|
+
Unless required by applicable law or agreed to in writing, software
|
|
191
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
192
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
193
|
+
See the License for the specific language governing permissions and
|
|
194
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
DuckDuckGo Search MCP - Modern README
|
|
3
|
+
Author: @OEvortex | License: Apache 2.0
|
|
4
|
+
-->
|
|
5
|
+
|
|
6
|
+
<div align="center">
|
|
7
|
+
<img src="https://img.shields.io/npm/v/@OEvortex/ddg_search.svg" alt="npm version" />
|
|
8
|
+
<img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License: Apache 2.0" />
|
|
9
|
+
<img src="https://img.shields.io/badge/YouTube-%40OEvortex-red.svg" alt="YouTube Channel" />
|
|
10
|
+
<h1>DuckDuckGo Search MCP 🔍</h1>
|
|
11
|
+
<p>A blazing-fast, privacy-friendly Model Context Protocol (MCP) server for web search and URL content extraction using DuckDuckGo.</p>
|
|
12
|
+
<a href="https://youtube.com/@OEvortex"><strong>Subscribe for updates & tutorials</strong></a>
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
> [!IMPORTANT]
|
|
18
|
+
> DuckDuckGo Search MCP supports two types of compatibility:
|
|
19
|
+
> - <b>Native MCP Compatibility:</b> Use the full power of the Model Context Protocol for maximum flexibility.
|
|
20
|
+
> - <b>OpenAI Compatibility:</b> Use with OpenAI-compatible interfaces and providers.
|
|
21
|
+
>
|
|
22
|
+
> Choose the approach that best fits your needs! For OpenAI compatibility, check the <a href="webscout/Provider/OPENAI/README.md">OpenAI Providers README</a>.
|
|
23
|
+
|
|
24
|
+
> [!NOTE]
|
|
25
|
+
> DuckDuckGo Search MCP is compatible with Claude, Anthropic, OpenAI, Perplexity, HuggingFace, LLAMA, and 90+ other AI providers. All providers follow similar usage patterns with consistent interfaces.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## ✨ Features
|
|
30
|
+
|
|
31
|
+
<div style="display: flex; flex-wrap: wrap; gap: 1.5em;">
|
|
32
|
+
<div><b>🌐 Web search</b> using DuckDuckGo HTML</div>
|
|
33
|
+
<div><b>📄 URL content extraction</b> with smart filtering</div>
|
|
34
|
+
<div><b>📊 URL metadata extraction</b> (title, description, images)</div>
|
|
35
|
+
<div><b>⚡ Performance optimized</b> with caching</div>
|
|
36
|
+
<div><b>🛡️ Security features</b> including rate limiting and rotating user agents</div>
|
|
37
|
+
<div><b>🔌 MCP-compliant</b> server implementation</div>
|
|
38
|
+
<div><b>🆓 No API keys required</b> - works out of the box</div>
|
|
39
|
+
</div>
|
|
40
|
+
|
|
41
|
+
> [!IMPORTANT]
|
|
42
|
+
> Unlike many search tools, this package performs actual web scraping rather than using limited APIs, giving you more comprehensive results.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## 🚀 Quick Start
|
|
47
|
+
|
|
48
|
+
<div style="background: #222; color: #fff; padding: 1em; border-radius: 8px;">
|
|
49
|
+
<b>Run instantly with npx:</b>
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npx -y @OEvortex/ddg_search
|
|
53
|
+
```
|
|
54
|
+
</div>
|
|
55
|
+
|
|
56
|
+
> [!TIP]
|
|
57
|
+
> This will download and run the MCP server directly without installation – perfect for quick use with Claude, OpenAI, or other AI assistants.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 🛠️ Installation Options
|
|
62
|
+
|
|
63
|
+
<details>
|
|
64
|
+
<summary><b>Global Installation</b></summary>
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
npm install -g @OEvortex/ddg_search
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Run globally:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
ddg-search-mcp
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
</details>
|
|
77
|
+
|
|
78
|
+
<details>
|
|
79
|
+
<summary><b>Local Installation (Development)</b></summary>
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
git clone https://github.com/OEvortex/ddg_search.git
|
|
83
|
+
cd ddg_search
|
|
84
|
+
npm install
|
|
85
|
+
npm start
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
</details>
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 🧑💻 Command Line Options
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
npx -y @OEvortex/ddg_search --help
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
> [!TIP]
|
|
99
|
+
> Use the <code>--version</code> flag to check which version you're running.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 🤖 Using with Claude, OpenAI, or Other MCP Clients
|
|
104
|
+
|
|
105
|
+
> [!IMPORTANT]
|
|
106
|
+
> The most common way to use this tool is by integrating it with Claude, OpenAI, or other MCP-compatible AI assistants.
|
|
107
|
+
|
|
108
|
+
Add the server to your MCP client configuration:
|
|
109
|
+
|
|
110
|
+
```json
|
|
111
|
+
{
|
|
112
|
+
"mcpServers": {
|
|
113
|
+
"ddg-search": {
|
|
114
|
+
"command": "npx",
|
|
115
|
+
"args": ["-y", "@OEvortex/ddg_search"]
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Or if installed globally:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"mcpServers": {
|
|
126
|
+
"ddg-search": {
|
|
127
|
+
"command": "ddg-search-mcp"
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
> [!TIP]
|
|
134
|
+
> After configuring, restart your Claude Desktop or other MCP client to apply the changes.
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## 🧰 Tools Overview
|
|
139
|
+
|
|
140
|
+
<div style="display: flex; flex-wrap: wrap; gap: 2em;">
|
|
141
|
+
<div>
|
|
142
|
+
<b>🔍 Web Search Tool</b><br/>
|
|
143
|
+
<code>web-search</code><br/>
|
|
144
|
+
<ul>
|
|
145
|
+
<li><b>query</b> (string, required): The search query</li>
|
|
146
|
+
<li><b>page</b> (integer, optional, default: 1): Page number</li>
|
|
147
|
+
<li><b>numResults</b> (integer, optional, default: 10): Number of results (1-20)</li>
|
|
148
|
+
</ul>
|
|
149
|
+
<i>Example: Search the web for "climate change solutions"</i>
|
|
150
|
+
</div>
|
|
151
|
+
<div>
|
|
152
|
+
<b>📄 Fetch URL Tool</b><br/>
|
|
153
|
+
<code>fetch-url</code><br/>
|
|
154
|
+
<ul>
|
|
155
|
+
<li><b>url</b> (string, required): The URL to fetch</li>
|
|
156
|
+
<li><b>maxLength</b> (integer, optional, default: 10000): Max content length</li>
|
|
157
|
+
<li><b>extractMainContent</b> (boolean, optional, default: true): Extract main content</li>
|
|
158
|
+
<li><b>includeLinks</b> (boolean, optional, default: true): Include link text</li>
|
|
159
|
+
<li><b>includeImages</b> (boolean, optional, default: true): Include image alt text</li>
|
|
160
|
+
<li><b>excludeTags</b> (array, optional): Tags to exclude</li>
|
|
161
|
+
</ul>
|
|
162
|
+
<i>Example: Fetch the content from "https://example.com"</i>
|
|
163
|
+
</div>
|
|
164
|
+
<div>
|
|
165
|
+
<b>📊 URL Metadata Tool</b><br/>
|
|
166
|
+
<code>url-metadata</code><br/>
|
|
167
|
+
<ul>
|
|
168
|
+
<li><b>url</b> (string, required): The URL to extract metadata from</li>
|
|
169
|
+
</ul>
|
|
170
|
+
<i>Example: Get metadata for "https://example.com"</i>
|
|
171
|
+
</div>
|
|
172
|
+
</div>
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## 📁 Project Structure
|
|
177
|
+
|
|
178
|
+
```text
|
|
179
|
+
bin/ # Command-line interface
|
|
180
|
+
src/
|
|
181
|
+
index.js # Main entry point
|
|
182
|
+
tools/ # Tool definitions and handlers
|
|
183
|
+
searchTool.js
|
|
184
|
+
fetchUrlTool.js
|
|
185
|
+
metadataTool.js
|
|
186
|
+
utils/
|
|
187
|
+
search.js # Search and URL utilities
|
|
188
|
+
package.json
|
|
189
|
+
README.md
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
## 🤝 Contributing
|
|
195
|
+
|
|
196
|
+
Contributions are welcome! Please open issues or submit pull requests.
|
|
197
|
+
|
|
198
|
+
> [!NOTE]
|
|
199
|
+
> Please follow the existing code style and add tests for new features.
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
## 📺 YouTube Channel
|
|
204
|
+
|
|
205
|
+
<div align="center">
|
|
206
|
+
<a href="https://youtube.com/@OEvortex"><img src="https://img.shields.io/badge/YouTube-%40OEvortex-red.svg" alt="YouTube Channel" /></a>
|
|
207
|
+
<br/>
|
|
208
|
+
<a href="https://youtube.com/@OEvortex">youtube.com/@OEvortex</a>
|
|
209
|
+
</div>
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## 📄 License
|
|
214
|
+
|
|
215
|
+
Apache License 2.0
|
|
216
|
+
|
|
217
|
+
> [!NOTE]
|
|
218
|
+
> This project is licensed under the Apache License 2.0 – see the <a href="LICENSE">LICENSE</a> file for details.
|
|
219
|
+
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
<div align="center">
|
|
223
|
+
<sub>Made with ❤️ by <a href="https://youtube.com/@OEvortex">@OEvortex</a></sub>
|
|
224
|
+
</div>
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
4
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
5
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
6
|
+
|
|
7
|
+
// Import tool definitions and handlers
|
|
8
|
+
const modulePath = new URL('../src', import.meta.url).pathname;
|
|
9
|
+
|
|
10
|
+
// Dynamic imports
|
|
11
|
+
async function startServer() {
|
|
12
|
+
try {
|
|
13
|
+
// Dynamically import the modules
|
|
14
|
+
const { searchToolDefinition, searchToolHandler } = await import(`${modulePath}/tools/searchTool.js`);
|
|
15
|
+
const { fetchUrlToolDefinition, fetchUrlToolHandler } = await import(`${modulePath}/tools/fetchUrlTool.js`);
|
|
16
|
+
const { metadataToolDefinition, metadataToolHandler } = await import(`${modulePath}/tools/metadataTool.js`);
|
|
17
|
+
|
|
18
|
+
// Create the MCP server
|
|
19
|
+
const server = new Server({
|
|
20
|
+
id: 'ddg-search-mcp',
|
|
21
|
+
name: 'DuckDuckGo Search MCP',
|
|
22
|
+
description: 'A Model Context Protocol server for web search using DuckDuckGo',
|
|
23
|
+
version: '1.0.0'
|
|
24
|
+
}, {
|
|
25
|
+
capabilities: {
|
|
26
|
+
tools: {}
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// Define available tools
|
|
31
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
32
|
+
return {
|
|
33
|
+
tools: [
|
|
34
|
+
searchToolDefinition,
|
|
35
|
+
fetchUrlToolDefinition,
|
|
36
|
+
metadataToolDefinition
|
|
37
|
+
]
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Handle tool execution
|
|
42
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
43
|
+
try {
|
|
44
|
+
const { name, arguments: args } = request.params;
|
|
45
|
+
|
|
46
|
+
// Route to the appropriate tool handler
|
|
47
|
+
switch (name) {
|
|
48
|
+
case 'web-search':
|
|
49
|
+
return await searchToolHandler(args);
|
|
50
|
+
|
|
51
|
+
case 'fetch-url':
|
|
52
|
+
return await fetchUrlToolHandler(args);
|
|
53
|
+
|
|
54
|
+
case 'url-metadata':
|
|
55
|
+
return await metadataToolHandler(args);
|
|
56
|
+
|
|
57
|
+
default:
|
|
58
|
+
throw new Error(`Tool not found: ${name}`);
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
console.error(`Error handling ${request.params.name} request:`, error);
|
|
62
|
+
return {
|
|
63
|
+
isError: true,
|
|
64
|
+
content: [
|
|
65
|
+
{
|
|
66
|
+
type: 'text',
|
|
67
|
+
text: `Error: ${error.message}`
|
|
68
|
+
}
|
|
69
|
+
]
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// Display promotional message
|
|
75
|
+
console.error('\n\x1b[36m╔════════════════════════════════════════════════════════════╗');
|
|
76
|
+
console.error('║ ║');
|
|
77
|
+
console.error('║ \x1b[1m\x1b[31mDuckDuckGo Search MCP\x1b[0m\x1b[36m by \x1b[1m\x1b[33m@OEvortex\x1b[0m\x1b[36m ║');
|
|
78
|
+
console.error('║ ║');
|
|
79
|
+
console.error('║ \x1b[0m👉 Subscribe to \x1b[1m\x1b[37myoutube.com/@OEvortex\x1b[0m\x1b[36m for more tools! ║');
|
|
80
|
+
console.error('║ ║');
|
|
81
|
+
console.error('╚════════════════════════════════════════════════════════════╝\x1b[0m\n');
|
|
82
|
+
|
|
83
|
+
// Start the server with stdio transport
|
|
84
|
+
const transport = new StdioServerTransport();
|
|
85
|
+
await server.connect(transport);
|
|
86
|
+
console.error('DuckDuckGo Search MCP server started and listening on stdio');
|
|
87
|
+
} catch (error) {
|
|
88
|
+
console.error('Failed to start server:', error);
|
|
89
|
+
process.exit(1);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Parse command line arguments
|
|
94
|
+
const args = process.argv.slice(2);
|
|
95
|
+
const helpFlag = args.includes('--help') || args.includes('-h');
|
|
96
|
+
const versionFlag = args.includes('--version') || args.includes('-v');
|
|
97
|
+
|
|
98
|
+
if (helpFlag) {
|
|
99
|
+
console.log(`
|
|
100
|
+
DuckDuckGo Search MCP - A Model Context Protocol server for web search
|
|
101
|
+
|
|
102
|
+
Usage:
|
|
103
|
+
npx -y @OEvortex/ddg_search [options]
|
|
104
|
+
|
|
105
|
+
Options:
|
|
106
|
+
-h, --help Show this help message
|
|
107
|
+
-v, --version Show version information
|
|
108
|
+
|
|
109
|
+
This MCP server provides the following tools:
|
|
110
|
+
- web-search: Search the web using DuckDuckGo
|
|
111
|
+
- fetch-url: Fetch and extract content from a URL
|
|
112
|
+
- url-metadata: Extract metadata from a URL
|
|
113
|
+
|
|
114
|
+
Created by @OEvortex
|
|
115
|
+
Subscribe to youtube.com/@OEvortex for more tools and tutorials!
|
|
116
|
+
|
|
117
|
+
For more information, visit: https://github.com/OEvortex/ddg_search
|
|
118
|
+
`);
|
|
119
|
+
process.exit(0);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (versionFlag) {
|
|
123
|
+
// Read version from package.json using fs
|
|
124
|
+
import('fs/promises')
|
|
125
|
+
.then(async ({ readFile }) => {
|
|
126
|
+
try {
|
|
127
|
+
const packageJson = JSON.parse(
|
|
128
|
+
await readFile(new URL('../package.json', import.meta.url), 'utf8')
|
|
129
|
+
);
|
|
130
|
+
console.log(`DuckDuckGo Search MCP v${packageJson.version}\nCreated by @OEvortex - Subscribe to youtube.com/@OEvortex!`);
|
|
131
|
+
process.exit(0);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
console.error('Error reading version information:', err);
|
|
134
|
+
process.exit(1);
|
|
135
|
+
}
|
|
136
|
+
})
|
|
137
|
+
.catch(err => {
|
|
138
|
+
console.error('Error importing fs module:', err);
|
|
139
|
+
process.exit(1);
|
|
140
|
+
});
|
|
141
|
+
} else {
|
|
142
|
+
// Start the server
|
|
143
|
+
startServer();
|
|
144
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@oevortex/ddg_search",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A Model Context Protocol server for web search using DuckDuckGo",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"bin": {
|
|
7
|
+
"ddg-search-mcp": "./bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
11
|
+
"start": "node bin/cli.js",
|
|
12
|
+
"prepublishOnly": "npm run lint",
|
|
13
|
+
"lint": "echo \"No linting configured\""
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"keywords": ["mcp", "model-context-protocol", "duckduckgo", "search", "web-search", "claude", "ai", "llm"],
|
|
19
|
+
"author": "OEvortex",
|
|
20
|
+
"license": "Apache-2.0",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@modelcontextprotocol/sdk": "^1.9.0",
|
|
24
|
+
"axios": "^1.8.4",
|
|
25
|
+
"cheerio": "^1.0.0",
|
|
26
|
+
"jsdom": "^26.1.0"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
|
|
5
|
+
// Import tool definitions and handlers
|
|
6
|
+
import { searchToolDefinition, searchToolHandler } from './tools/searchTool.js';
|
|
7
|
+
import { fetchUrlToolDefinition, fetchUrlToolHandler } from './tools/fetchUrlTool.js';
|
|
8
|
+
import { metadataToolDefinition, metadataToolHandler } from './tools/metadataTool.js';
|
|
9
|
+
|
|
10
|
+
// Create the MCP server
|
|
11
|
+
const server = new Server({
|
|
12
|
+
id: 'websearch-mcp',
|
|
13
|
+
name: 'WebSearch MCP',
|
|
14
|
+
description: 'A Model Context Protocol server for web search using DuckDuckGo',
|
|
15
|
+
version: '1.0.0'
|
|
16
|
+
}, {
|
|
17
|
+
capabilities: {
|
|
18
|
+
tools: {}
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// Define available tools
|
|
23
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
24
|
+
return {
|
|
25
|
+
tools: [
|
|
26
|
+
searchToolDefinition,
|
|
27
|
+
fetchUrlToolDefinition,
|
|
28
|
+
metadataToolDefinition
|
|
29
|
+
]
|
|
30
|
+
};
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// Handle tool execution
|
|
34
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
35
|
+
try {
|
|
36
|
+
const { name, arguments: args } = request.params;
|
|
37
|
+
|
|
38
|
+
// Route to the appropriate tool handler
|
|
39
|
+
switch (name) {
|
|
40
|
+
case 'web-search':
|
|
41
|
+
return await searchToolHandler(args);
|
|
42
|
+
|
|
43
|
+
case 'fetch-url':
|
|
44
|
+
return await fetchUrlToolHandler(args);
|
|
45
|
+
|
|
46
|
+
case 'url-metadata':
|
|
47
|
+
return await metadataToolHandler(args);
|
|
48
|
+
|
|
49
|
+
default:
|
|
50
|
+
throw new Error(`Tool not found: ${name}`);
|
|
51
|
+
}
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.error(`Error handling ${request.params.name} request:`, error);
|
|
54
|
+
return {
|
|
55
|
+
isError: true,
|
|
56
|
+
content: [
|
|
57
|
+
{
|
|
58
|
+
type: 'text',
|
|
59
|
+
text: `Error: ${error.message}`
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// Start the server with stdio transport
|
|
67
|
+
async function main() {
|
|
68
|
+
try {
|
|
69
|
+
const transport = new StdioServerTransport();
|
|
70
|
+
await server.connect(transport);
|
|
71
|
+
console.error('WebSearch MCP server started and listening on stdio');
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error('Failed to start server:', error);
|
|
74
|
+
process.exit(1);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
main();
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { fetchUrlContent } from '../utils/search.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Fetch URL tool definition
|
|
5
|
+
*/
|
|
6
|
+
export const fetchUrlToolDefinition = {
|
|
7
|
+
name: 'fetch-url',
|
|
8
|
+
description: 'Fetch the content of a URL and return it as text, with options to control extraction',
|
|
9
|
+
inputSchema: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
url: {
|
|
13
|
+
type: 'string',
|
|
14
|
+
description: 'The URL to fetch'
|
|
15
|
+
},
|
|
16
|
+
maxLength: {
|
|
17
|
+
type: 'integer',
|
|
18
|
+
description: 'Maximum length of content to return (default: 10000)',
|
|
19
|
+
default: 10000,
|
|
20
|
+
minimum: 1000,
|
|
21
|
+
maximum: 50000
|
|
22
|
+
},
|
|
23
|
+
extractMainContent: {
|
|
24
|
+
type: 'boolean',
|
|
25
|
+
description: 'Whether to attempt to extract main content (default: true)',
|
|
26
|
+
default: true
|
|
27
|
+
},
|
|
28
|
+
includeLinks: {
|
|
29
|
+
type: 'boolean',
|
|
30
|
+
description: 'Whether to include link text (default: true)',
|
|
31
|
+
default: true
|
|
32
|
+
},
|
|
33
|
+
includeImages: {
|
|
34
|
+
type: 'boolean',
|
|
35
|
+
description: 'Whether to include image alt text (default: true)',
|
|
36
|
+
default: true
|
|
37
|
+
},
|
|
38
|
+
excludeTags: {
|
|
39
|
+
type: 'array',
|
|
40
|
+
description: 'Tags to exclude from extraction (default: script, style, etc.)',
|
|
41
|
+
items: {
|
|
42
|
+
type: 'string'
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
required: ['url']
|
|
47
|
+
},
|
|
48
|
+
annotations: {
|
|
49
|
+
title: 'Fetch URL Content',
|
|
50
|
+
readOnlyHint: true,
|
|
51
|
+
openWorldHint: true
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Fetch URL tool handler
|
|
57
|
+
* @param {Object} params - The tool parameters
|
|
58
|
+
* @returns {Promise<Object>} - The tool result
|
|
59
|
+
*/
|
|
60
|
+
export async function fetchUrlToolHandler(params) {
|
|
61
|
+
const {
|
|
62
|
+
url,
|
|
63
|
+
maxLength = 10000,
|
|
64
|
+
extractMainContent = true,
|
|
65
|
+
includeLinks = true,
|
|
66
|
+
includeImages = true,
|
|
67
|
+
excludeTags = ['script', 'style', 'noscript', 'iframe', 'svg', 'nav', 'footer', 'header', 'aside']
|
|
68
|
+
} = params;
|
|
69
|
+
|
|
70
|
+
console.log(`Fetching content from URL: ${url} (maxLength: ${maxLength})`);
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
// Fetch content with specified options
|
|
74
|
+
const content = await fetchUrlContent(url, {
|
|
75
|
+
extractMainContent,
|
|
76
|
+
includeLinks,
|
|
77
|
+
includeImages,
|
|
78
|
+
excludeTags
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Truncate content if it's too long
|
|
82
|
+
const truncatedContent = content.length > maxLength
|
|
83
|
+
? content.substring(0, maxLength) + '... [Content truncated due to length]'
|
|
84
|
+
: content;
|
|
85
|
+
|
|
86
|
+
// Add metadata about the extraction
|
|
87
|
+
const metadata = `
|
|
88
|
+
---
|
|
89
|
+
Extraction settings:
|
|
90
|
+
- URL: ${url}
|
|
91
|
+
- Main content extraction: ${extractMainContent ? 'Enabled' : 'Disabled'}
|
|
92
|
+
- Links included: ${includeLinks ? 'Yes' : 'No'}
|
|
93
|
+
- Images included: ${includeImages ? 'Yes (as alt text)' : 'No'}
|
|
94
|
+
- Content length: ${content.length} characters${content.length > maxLength ? ` (truncated to ${maxLength})` : ''}
|
|
95
|
+
---
|
|
96
|
+
`;
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
content: [
|
|
100
|
+
{
|
|
101
|
+
type: 'text',
|
|
102
|
+
text: truncatedContent + metadata
|
|
103
|
+
}
|
|
104
|
+
]
|
|
105
|
+
};
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error(`Error fetching URL ${url}:`, error);
|
|
108
|
+
return {
|
|
109
|
+
isError: true,
|
|
110
|
+
content: [
|
|
111
|
+
{
|
|
112
|
+
type: 'text',
|
|
113
|
+
text: `Error fetching URL: ${error.message}`
|
|
114
|
+
}
|
|
115
|
+
]
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { extractUrlMetadata } from '../utils/search.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* URL metadata tool definition
|
|
5
|
+
*/
|
|
6
|
+
export const metadataToolDefinition = {
|
|
7
|
+
name: 'url-metadata',
|
|
8
|
+
description: 'Extract metadata from a URL (title, description, etc.)',
|
|
9
|
+
inputSchema: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
url: {
|
|
13
|
+
type: 'string',
|
|
14
|
+
description: 'The URL to extract metadata from'
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
required: ['url']
|
|
18
|
+
},
|
|
19
|
+
annotations: {
|
|
20
|
+
title: 'URL Metadata',
|
|
21
|
+
readOnlyHint: true,
|
|
22
|
+
openWorldHint: true
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* URL metadata tool handler
|
|
28
|
+
* @param {Object} params - The tool parameters
|
|
29
|
+
* @returns {Promise<Object>} - The tool result
|
|
30
|
+
*/
|
|
31
|
+
export async function metadataToolHandler(params) {
|
|
32
|
+
const { url } = params;
|
|
33
|
+
console.log(`Extracting metadata from URL: ${url}`);
|
|
34
|
+
|
|
35
|
+
const metadata = await extractUrlMetadata(url);
|
|
36
|
+
|
|
37
|
+
// Format the metadata for display
|
|
38
|
+
const formattedMetadata = `
|
|
39
|
+
## URL Metadata for ${url}
|
|
40
|
+
|
|
41
|
+
**Title:** ${metadata.title}
|
|
42
|
+
|
|
43
|
+
**Description:** ${metadata.description}
|
|
44
|
+
|
|
45
|
+
**Image:** ${metadata.ogImage || 'None'}
|
|
46
|
+
|
|
47
|
+
**Favicon:** ${metadata.favicon || 'None'}
|
|
48
|
+
`.trim();
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
content: [
|
|
52
|
+
{
|
|
53
|
+
type: 'text',
|
|
54
|
+
text: formattedMetadata
|
|
55
|
+
}
|
|
56
|
+
]
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { searchDuckDuckGo } from '../utils/search.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Web search tool definition
|
|
5
|
+
*/
|
|
6
|
+
export const searchToolDefinition = {
|
|
7
|
+
name: 'web-search',
|
|
8
|
+
description: 'Search the web using DuckDuckGo and return results',
|
|
9
|
+
inputSchema: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
query: {
|
|
13
|
+
type: 'string',
|
|
14
|
+
description: 'The search query'
|
|
15
|
+
},
|
|
16
|
+
page: {
|
|
17
|
+
type: 'integer',
|
|
18
|
+
description: 'Page number (default: 1)',
|
|
19
|
+
default: 1,
|
|
20
|
+
minimum: 1
|
|
21
|
+
},
|
|
22
|
+
numResults: {
|
|
23
|
+
type: 'integer',
|
|
24
|
+
description: 'Number of results to return (default: 10)',
|
|
25
|
+
default: 10,
|
|
26
|
+
minimum: 1,
|
|
27
|
+
maximum: 20
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
required: ['query']
|
|
31
|
+
},
|
|
32
|
+
annotations: {
|
|
33
|
+
title: 'Web Search',
|
|
34
|
+
readOnlyHint: true,
|
|
35
|
+
openWorldHint: true
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Web search tool handler
|
|
41
|
+
* @param {Object} params - The tool parameters
|
|
42
|
+
* @returns {Promise<Object>} - The tool result
|
|
43
|
+
*/
|
|
44
|
+
export async function searchToolHandler(params) {
|
|
45
|
+
const { query, page = 1, numResults = 10 } = params;
|
|
46
|
+
console.log(`Searching for: ${query} (page ${page}, ${numResults} results)`);
|
|
47
|
+
|
|
48
|
+
const results = await searchDuckDuckGo(query, page, numResults);
|
|
49
|
+
console.log(`Found ${results.length} results`);
|
|
50
|
+
|
|
51
|
+
// Format the results for display
|
|
52
|
+
const formattedResults = results.map((result, index) =>
|
|
53
|
+
`${index + 1}. [${result.title}](${result.url})\n ${result.snippet}`
|
|
54
|
+
).join('\n\n');
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
content: [
|
|
58
|
+
{
|
|
59
|
+
type: 'text',
|
|
60
|
+
text: formattedResults || 'No results found.'
|
|
61
|
+
}
|
|
62
|
+
]
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import { JSDOM } from 'jsdom';
|
|
3
|
+
|
|
4
|
+
// Constants
|
|
5
|
+
const RESULTS_PER_PAGE = 10;
|
|
6
|
+
const MAX_CACHE_PAGES = 5;
|
|
7
|
+
|
|
8
|
+
// Rotating User Agents
|
|
9
|
+
const USER_AGENTS = [
|
|
10
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
|
11
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Edge/120.0.0.0',
|
|
12
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2.1 Safari/605.1.15',
|
|
13
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0',
|
|
14
|
+
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
// Cache results to avoid repeated requests
|
|
18
|
+
const resultsCache = new Map();
|
|
19
|
+
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Get a random user agent from the list
|
|
23
|
+
* @returns {string} A random user agent string
|
|
24
|
+
*/
|
|
25
|
+
function getRandomUserAgent() {
|
|
26
|
+
return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Generate a cache key for a search query and page
|
|
31
|
+
* @param {string} query - The search query
|
|
32
|
+
* @param {number} page - The page number
|
|
33
|
+
* @returns {string} The cache key
|
|
34
|
+
*/
|
|
35
|
+
function getCacheKey(query, page) {
|
|
36
|
+
return `${query}-${page}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Clear old entries from the cache
|
|
41
|
+
*/
|
|
42
|
+
function clearOldCache() {
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
for (const [key, value] of resultsCache.entries()) {
|
|
45
|
+
if (now - value.timestamp > CACHE_DURATION) {
|
|
46
|
+
resultsCache.delete(key);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Extract the direct URL from a DuckDuckGo redirect URL
|
|
53
|
+
* @param {string} duckduckgoUrl - The DuckDuckGo URL to extract from
|
|
54
|
+
* @returns {string} The direct URL
|
|
55
|
+
*/
|
|
56
|
+
function extractDirectUrl(duckduckgoUrl) {
|
|
57
|
+
try {
|
|
58
|
+
// Handle relative URLs from DuckDuckGo
|
|
59
|
+
if (duckduckgoUrl.startsWith('//')) {
|
|
60
|
+
duckduckgoUrl = 'https:' + duckduckgoUrl;
|
|
61
|
+
} else if (duckduckgoUrl.startsWith('/')) {
|
|
62
|
+
duckduckgoUrl = 'https://duckduckgo.com' + duckduckgoUrl;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const url = new URL(duckduckgoUrl);
|
|
66
|
+
|
|
67
|
+
// Extract direct URL from DuckDuckGo redirect
|
|
68
|
+
if (url.hostname === 'duckduckgo.com' && url.pathname === '/l/') {
|
|
69
|
+
const uddg = url.searchParams.get('uddg');
|
|
70
|
+
if (uddg) {
|
|
71
|
+
return decodeURIComponent(uddg);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Handle ad redirects
|
|
76
|
+
if (url.hostname === 'duckduckgo.com' && url.pathname === '/y.js') {
|
|
77
|
+
const u3 = url.searchParams.get('u3');
|
|
78
|
+
if (u3) {
|
|
79
|
+
try {
|
|
80
|
+
const decodedU3 = decodeURIComponent(u3);
|
|
81
|
+
const u3Url = new URL(decodedU3);
|
|
82
|
+
const clickUrl = u3Url.searchParams.get('ld');
|
|
83
|
+
if (clickUrl) {
|
|
84
|
+
return decodeURIComponent(clickUrl);
|
|
85
|
+
}
|
|
86
|
+
return decodedU3;
|
|
87
|
+
} catch {
|
|
88
|
+
return duckduckgoUrl;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return duckduckgoUrl;
|
|
94
|
+
} catch {
|
|
95
|
+
// If URL parsing fails, try to extract URL from a basic string match
|
|
96
|
+
const urlMatch = duckduckgoUrl.match(/https?:\/\/[^\s<>"]+/);
|
|
97
|
+
if (urlMatch) {
|
|
98
|
+
return urlMatch[0];
|
|
99
|
+
}
|
|
100
|
+
return duckduckgoUrl;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Get a favicon URL for a given website URL
|
|
106
|
+
* @param {string} url - The website URL
|
|
107
|
+
* @returns {string} The favicon URL
|
|
108
|
+
*/
|
|
109
|
+
function getFaviconUrl(url) {
|
|
110
|
+
try {
|
|
111
|
+
const urlObj = new URL(url);
|
|
112
|
+
return `https://www.google.com/s2/favicons?domain=${urlObj.hostname}&sz=32`;
|
|
113
|
+
} catch {
|
|
114
|
+
return ''; // Return empty string if URL is invalid
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Scrapes search results from DuckDuckGo HTML
|
|
120
|
+
* @param {string} query - The search query
|
|
121
|
+
* @param {number} page - The page number (default: 1)
|
|
122
|
+
* @param {number} numResults - Number of results to return (default: 10)
|
|
123
|
+
* @returns {Promise<Array>} - Array of search results
|
|
124
|
+
*/
|
|
125
|
+
async function searchDuckDuckGo(query, page = 1, numResults = 10) {
|
|
126
|
+
try {
|
|
127
|
+
// Clear old cache entries
|
|
128
|
+
clearOldCache();
|
|
129
|
+
|
|
130
|
+
// Calculate start index for pagination
|
|
131
|
+
const startIndex = (page - 1) * RESULTS_PER_PAGE;
|
|
132
|
+
|
|
133
|
+
// Check cache first
|
|
134
|
+
const cacheKey = getCacheKey(query, page);
|
|
135
|
+
const cachedResults = resultsCache.get(cacheKey);
|
|
136
|
+
|
|
137
|
+
if (cachedResults && Date.now() - cachedResults.timestamp < CACHE_DURATION) {
|
|
138
|
+
return cachedResults.results.slice(0, numResults);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Get a random user agent
|
|
142
|
+
const userAgent = getRandomUserAgent();
|
|
143
|
+
|
|
144
|
+
// Fetch results
|
|
145
|
+
const response = await axios.get(
|
|
146
|
+
`https://duckduckgo.com/html/?q=${encodeURIComponent(query)}&s=${startIndex}`,
|
|
147
|
+
{
|
|
148
|
+
headers: {
|
|
149
|
+
'User-Agent': userAgent
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
if (response.status !== 200) {
|
|
155
|
+
throw new Error('Failed to fetch search results');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const html = response.data;
|
|
159
|
+
|
|
160
|
+
// Parse results using JSDOM
|
|
161
|
+
const dom = new JSDOM(html);
|
|
162
|
+
const document = dom.window.document;
|
|
163
|
+
|
|
164
|
+
const results = [];
|
|
165
|
+
const searchResults = document.querySelectorAll('.result');
|
|
166
|
+
|
|
167
|
+
searchResults.forEach((result) => {
|
|
168
|
+
const titleEl = result.querySelector('.result__title a');
|
|
169
|
+
const linkEl = result.querySelector('.result__url');
|
|
170
|
+
const snippetEl = result.querySelector('.result__snippet');
|
|
171
|
+
|
|
172
|
+
const title = titleEl?.textContent?.trim();
|
|
173
|
+
const rawLink = titleEl?.getAttribute('href');
|
|
174
|
+
const description = snippetEl?.textContent?.trim();
|
|
175
|
+
const displayUrl = linkEl?.textContent?.trim();
|
|
176
|
+
|
|
177
|
+
const directLink = extractDirectUrl(rawLink || '');
|
|
178
|
+
const favicon = getFaviconUrl(directLink);
|
|
179
|
+
|
|
180
|
+
if (title && directLink) {
|
|
181
|
+
results.push({
|
|
182
|
+
title,
|
|
183
|
+
url: directLink,
|
|
184
|
+
snippet: description || '',
|
|
185
|
+
favicon: favicon,
|
|
186
|
+
displayUrl: displayUrl || ''
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// Get paginated results
|
|
192
|
+
const paginatedResults = results.slice(0, numResults);
|
|
193
|
+
|
|
194
|
+
// Cache the results
|
|
195
|
+
resultsCache.set(cacheKey, {
|
|
196
|
+
results: paginatedResults,
|
|
197
|
+
timestamp: Date.now()
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
// If cache is too big, remove oldest entries
|
|
201
|
+
if (resultsCache.size > MAX_CACHE_PAGES) {
|
|
202
|
+
const oldestKey = Array.from(resultsCache.keys())[0];
|
|
203
|
+
resultsCache.delete(oldestKey);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return paginatedResults;
|
|
207
|
+
} catch (error) {
|
|
208
|
+
console.error('Error searching DuckDuckGo:', error.message);
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Fetches the content of a URL and returns it as text
|
|
215
|
+
* @param {string} url - The URL to fetch
|
|
216
|
+
* @param {Object} options - Options for content extraction
|
|
217
|
+
* @param {boolean} options.extractMainContent - Whether to attempt to extract main content (default: true)
|
|
218
|
+
* @param {boolean} options.includeLinks - Whether to include link text (default: true)
|
|
219
|
+
* @param {boolean} options.includeImages - Whether to include image alt text (default: true)
|
|
220
|
+
* @param {string[]} options.excludeTags - Tags to exclude from extraction
|
|
221
|
+
* @returns {Promise<string>} - The content of the URL
|
|
222
|
+
*/
|
|
223
|
+
async function fetchUrlContent(url, options = {}) {
|
|
224
|
+
try {
|
|
225
|
+
// Default options
|
|
226
|
+
const {
|
|
227
|
+
extractMainContent = true,
|
|
228
|
+
includeLinks = true,
|
|
229
|
+
includeImages = true,
|
|
230
|
+
excludeTags = ['script', 'style', 'noscript', 'iframe', 'svg', 'nav', 'footer', 'header', 'aside']
|
|
231
|
+
} = options;
|
|
232
|
+
|
|
233
|
+
// Get a random user agent
|
|
234
|
+
const userAgent = getRandomUserAgent();
|
|
235
|
+
|
|
236
|
+
const response = await axios.get(url, {
|
|
237
|
+
headers: {
|
|
238
|
+
'User-Agent': userAgent
|
|
239
|
+
},
|
|
240
|
+
timeout: 10000 // 10 second timeout
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
if (response.status !== 200) {
|
|
244
|
+
throw new Error(`Failed to fetch URL: ${url}`);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// If the content is HTML, extract the text content
|
|
248
|
+
const contentType = response.headers['content-type'] || '';
|
|
249
|
+
if (contentType.includes('text/html')) {
|
|
250
|
+
const dom = new JSDOM(response.data);
|
|
251
|
+
const document = dom.window.document;
|
|
252
|
+
|
|
253
|
+
// Remove unwanted elements
|
|
254
|
+
excludeTags.forEach(tag => {
|
|
255
|
+
const elements = document.querySelectorAll(tag);
|
|
256
|
+
elements.forEach(el => el.remove());
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
// Remove ads and other common unwanted elements
|
|
260
|
+
const unwantedSelectors = [
|
|
261
|
+
'[id*="ad"]', '[class*="ad"]', '[id*="banner"]', '[class*="banner"]',
|
|
262
|
+
'[id*="popup"]', '[class*="popup"]', '[class*="cookie"]',
|
|
263
|
+
'[id*="cookie"]', '[class*="newsletter"]', '[id*="newsletter"]',
|
|
264
|
+
'[class*="social"]', '[id*="social"]', '[class*="share"]', '[id*="share"]'
|
|
265
|
+
];
|
|
266
|
+
|
|
267
|
+
unwantedSelectors.forEach(selector => {
|
|
268
|
+
try {
|
|
269
|
+
const elements = document.querySelectorAll(selector);
|
|
270
|
+
elements.forEach(el => el.remove());
|
|
271
|
+
} catch (e) {
|
|
272
|
+
// Ignore invalid selectors
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
// Handle links and images
|
|
277
|
+
if (!includeLinks) {
|
|
278
|
+
const links = document.querySelectorAll('a');
|
|
279
|
+
links.forEach(link => {
|
|
280
|
+
const span = document.createElement('span');
|
|
281
|
+
span.textContent = link.textContent;
|
|
282
|
+
link.parentNode.replaceChild(span, link);
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (!includeImages) {
|
|
287
|
+
const images = document.querySelectorAll('img');
|
|
288
|
+
images.forEach(img => img.remove());
|
|
289
|
+
} else {
|
|
290
|
+
// Replace images with their alt text
|
|
291
|
+
const images = document.querySelectorAll('img');
|
|
292
|
+
images.forEach(img => {
|
|
293
|
+
const alt = img.getAttribute('alt');
|
|
294
|
+
if (alt) {
|
|
295
|
+
const span = document.createElement('span');
|
|
296
|
+
span.textContent = `[Image: ${alt}]`;
|
|
297
|
+
img.parentNode.replaceChild(span, img);
|
|
298
|
+
} else {
|
|
299
|
+
img.remove();
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Try to extract main content if requested
|
|
305
|
+
if (extractMainContent) {
|
|
306
|
+
// Common content selectors in order of priority
|
|
307
|
+
const contentSelectors = [
|
|
308
|
+
'article', 'main', '[role="main"]', '.post-content', '.article-content',
|
|
309
|
+
'.content', '#content', '.post', '.article', '.entry-content',
|
|
310
|
+
'.page-content', '.post-body', '.post-text', '.story-body'
|
|
311
|
+
];
|
|
312
|
+
|
|
313
|
+
for (const selector of contentSelectors) {
|
|
314
|
+
const mainContent = document.querySelector(selector);
|
|
315
|
+
if (mainContent) {
|
|
316
|
+
// Clean up the content
|
|
317
|
+
return cleanText(mainContent.textContent);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// If no main content found or not requested, use the body
|
|
323
|
+
return cleanText(document.body.textContent);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// For non-HTML content, return as is
|
|
327
|
+
return response.data.toString();
|
|
328
|
+
} catch (error) {
|
|
329
|
+
console.error('Error fetching URL content:', error.message);
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Cleans up text by removing excessive whitespace and normalizing line breaks
|
|
336
|
+
* @param {string} text - The text to clean
|
|
337
|
+
* @returns {string} - The cleaned text
|
|
338
|
+
*/
|
|
339
|
+
function cleanText(text) {
|
|
340
|
+
return text
|
|
341
|
+
.replace(/\s+/g, ' ') // Replace multiple whitespace with single space
|
|
342
|
+
.replace(/\n\s*\n/g, '\n\n') // Normalize multiple line breaks
|
|
343
|
+
.replace(/^\s+|\s+$/g, '') // Trim start and end
|
|
344
|
+
.trim();
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Extracts metadata from a URL (title, description, etc.)
|
|
349
|
+
* @param {string} url - The URL to extract metadata from
|
|
350
|
+
* @returns {Promise<Object>} - The metadata
|
|
351
|
+
*/
|
|
352
|
+
async function extractUrlMetadata(url) {
|
|
353
|
+
try {
|
|
354
|
+
// Get a random user agent
|
|
355
|
+
const userAgent = getRandomUserAgent();
|
|
356
|
+
|
|
357
|
+
const response = await axios.get(url, {
|
|
358
|
+
headers: {
|
|
359
|
+
'User-Agent': userAgent
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
if (response.status !== 200) {
|
|
364
|
+
throw new Error(`Failed to fetch URL: ${url}`);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const dom = new JSDOM(response.data);
|
|
368
|
+
const document = dom.window.document;
|
|
369
|
+
|
|
370
|
+
// Extract metadata
|
|
371
|
+
const title = document.querySelector('title')?.textContent || '';
|
|
372
|
+
const description = document.querySelector('meta[name="description"]')?.getAttribute('content') ||
|
|
373
|
+
document.querySelector('meta[property="og:description"]')?.getAttribute('content') || '';
|
|
374
|
+
const ogImage = document.querySelector('meta[property="og:image"]')?.getAttribute('content') || '';
|
|
375
|
+
const favicon = document.querySelector('link[rel="icon"]')?.getAttribute('href') ||
|
|
376
|
+
document.querySelector('link[rel="shortcut icon"]')?.getAttribute('href') || '';
|
|
377
|
+
|
|
378
|
+
// Resolve relative URLs
|
|
379
|
+
const resolvedFavicon = favicon ? new URL(favicon, url).href : getFaviconUrl(url);
|
|
380
|
+
const resolvedOgImage = ogImage ? new URL(ogImage, url).href : '';
|
|
381
|
+
|
|
382
|
+
return {
|
|
383
|
+
title,
|
|
384
|
+
description,
|
|
385
|
+
ogImage: resolvedOgImage,
|
|
386
|
+
favicon: resolvedFavicon,
|
|
387
|
+
url
|
|
388
|
+
};
|
|
389
|
+
} catch (error) {
|
|
390
|
+
console.error('Error extracting URL metadata:', error.message);
|
|
391
|
+
throw error;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export {
|
|
396
|
+
searchDuckDuckGo,
|
|
397
|
+
fetchUrlContent,
|
|
398
|
+
extractUrlMetadata,
|
|
399
|
+
extractDirectUrl,
|
|
400
|
+
getFaviconUrl
|
|
401
|
+
};
|