Skip to main content
Glama
Biogod2020
by Biogod2020

dsh-bing-search

简体中文

Веб-поиск для DeepSeek Harness (DSH), реализованный как небольшой MCP-сервер на базе curl_cffi.

Порядок search:

  1. Проверяет доступность HTML-версии DuckDuckGo (html.duckduckgo.com) и кэширует результат примерно на 60 секунд. Из материкового Китая эта проверка часто не проходит без настройки прокси.

  2. Использует DDG, когда он доступен.

  3. Переключается на Bing, когда DDG недоступен, ограничен по частоте запросов (HTTP 202 / challenge) или набор результатов имеет quality_label=poor.

  4. Направляет Bing в зависимости от языка: для китайского и рынков zh-* используется cn.bing.com, в остальных случаях — www.bing.com.

Каждый ответ поиска включает quality_score (0–1) и quality_label (good / weak / poor). Считайте poor непригодным к использованию (словарные страницы, мусор из первых токенов). Не цитируйте такие заголовки.

Плагин предоставляет агенту DSH три инструмента в стиле браузера:

  • mcp__web__search — поиск по публичному вебу и возврат нормализованных органических результатов.

  • mcp__web__open — открыть публичную веб-страницу и извлечь читаемый текст.

  • mcp__web__find — найти текст на длинной странице и вернуть окружающий контекст.

DSH agent
  -> @deepseek-ai/dsh-mcp-client
  -> dsh-bing-search (MCP/stdio)
  -> curl_cffi.AsyncSession(impersonate="chrome")
  -> html.duckduckgo.com          (if reachable)
  -> else cn.bing.com / www.bing.com

Материковый Китай: без прокси или VPN DuckDuckGo часто недоступен. Это ожидаемо. В этом случае плагин использует Bing и устанавливает warnings в duckduckgo_unreachable. Дочерний MCP-процесс не наследует переменные HTTP_PROXY / HTTPS_PROXY из вашего shell (trust_env=False). Чтобы принудительно задать прокси, установите DSH_WEB_PROXY в процессе плагина (например, http://127.0.0.1:10808 в карте env: в cordis). Не рассчитывайте, что DDG будет работать в типичной домашней или университетской сети материкового Китая.

Сообщество плагинов: DeepSeek Harness просит сторонние плагины использовать тему dsh-plugin на GitHub для обнаружения.

Самая быстрая установка: передайте этот репозиторий агенту

Если ваш пишущий код агент имеет доступ к терминалу и файловой системе (Codex, Claude Code, Pi, OpenCode и т.д.), вставьте следующее:

Install this DeepSeek Harness plugin into my current DSH setup:
https://github.com/Biogod2020/dsh-bing-search

Read the repository README and INSTALL.md first. Install it with uv, detect my active
DSH profile, add it through cordis.patch.yml using the required `insert` patch form,
preserve all unrelated config, use the absolute path of the installed dsh-bing-search
executable, then verify that mcp__web__search, mcp__web__open, and mcp__web__find are
registered. Finally run one real web search smoke test and report what changed.

Это рекомендуемый путь. INSTALL.md содержит детерминированный контракт установки, написанный для агентов.

Related MCP server: webmcp

Установка вручную

1. Установите исполняемый файл

Требуется Python 3.10 или новее. С помощью uv:

uv tool install --force git+https://github.com/Biogod2020/dsh-bing-search.git

Найдите каталог bin инструмента:

uv tool dir --bin

Используйте абсолютный путь к dsh-bing-search (или dsh-bing-search.exe в Windows) в конфигурации DSH ниже.

Для разработки вместо установки как инструмента:

git clone https://github.com/Biogod2020/dsh-bing-search.git
cd dsh-bing-search
uv sync --extra dev

Репозиторий включает uv.lock для воспроизводимых установок в режиме разработки.

2. Добавьте его в DSH

Профили DSH объединяют корневой cordis.yml со слоем патчей cordis.patch.yml. При добавлении нового плагина через слой патчей запись обязательно должна быть обёрнута в insert:

- insert:
    - id: mcp-web
      name: '@deepseek-ai/dsh-mcp-client'
      config:
        serverName: web
        transport: stdio
        command: /ABSOLUTE/PATH/TO/dsh-bing-search
        args: []
        toolCallTimeoutMs: 30000
        failOnStartupError: true
        reconnect:
          enabled: true
          initialDelayMs: 500
          maxDelayMs: 30000
          maxAttempts: 10

Не добавляйте запись - id: mcp-web в cordis.patch.yml без обёртки: такие записи патчат существующие ID, а неизвестный ID может быть пропущен. Если вы редактируете корневой cordis.yml напрямую, обычная запись плагина без обёртки — правильный вариант. См. cordis.example.yml.

3. Проверка

После перезагрузки профиля DSH модель должна увидеть:

mcp__web__search
mcp__web__open
mcp__web__find

Затем попросите агента найти что-то актуальное и открыть один результат. Успешный цикл подтверждает и доступ к поиску, и регистрацию в MCP. Перезапустите DSH (или дочерний MCP-процесс) после изменения кода плагина; процесс stdio не перезагружает Python на лету.

Инструменты

{
  "query": "DeepSeek Harness GitHub",
  "count": 8,
  "offset": 0,
  "market": "en-US",
  "safe_search": "Moderate"
}

Возвращает:

Поле

Значение

provider

duckduckgo или bing

title / url / snippet / rank

Органический результат

source_id

Стабильный ID из канонического URL

quality_score

Пересечение запроса с заголовками/сниппетами от 0 до 1

quality_label

good / weak / poor

warnings

Причина переключения и заметки о качестве

Используйте market=zh-CN для китайских запросов. Если запрос содержит символы CJK, запасной вариант Bing всё равно использует cn.bing.com, даже если market установлен в en-US.

Редиректы DuckDuckGo /l/?uddg= и Bing /ck/a декодируются там, где это возможно. Распространённые отслеживающие параметры удаляются, а дублирующиеся URL объединяются.

Для людей, статей или иллюстрированных блогов сначала ищите имя автора или короткое имя собственное. Если quality_label — poor, не продолжайте удлинять запрос. Китайские академические метаданные относятся к специализированному корпусу (например, CNKI), а не к этому общему веб-поиску.

open

{
  "url": "https://example.com/article",
  "max_chars": 24000
}

Загружает публичные HTTP(S)-страницы с помощью curl_cffi, применяет проверки DNS/IP и безопасные редиректы, ограничивает размер ответа и извлекает читаемый текст без выполнения JavaScript.

open предназначен для HTML, похожего на статьи. Это не браузер. Живые запуски DSH показали, что погодные и другие сайты с большим количеством виджетов (tianqi.com, weather.com.cn и подобные) часто возвращают навигационные элементы или почти пустой текст: Trafilatura не находит основную статью, и запасной вариант выгружает весь DOM. status при этом может быть ok. Для таких страниц доверяйте сниппету из поиска или открывайте более простой URL статьи. Не ожидайте живую температуру, карты или другой JS-рендеринг.

find

{
  "url": "https://example.com/article",
  "pattern": "DeepSeek",
  "max_matches": 5,
  "context_chars": 700
}

Возвращает соответствующие фрагменты, не вставляя всю страницу в контекст модели.

Почему три инструмента вместо одного большого search_and_summarize?

Плагин сохраняет детерминированный поиск и позволяет модели DSH управлять циклом исследования:

search -> inspect candidates -> open -> find / search again -> synthesize

Плагин обрабатывает HTTP, парсинг, очистку, кэширование, переключение движков, происхождение данных и оценку качества. Агент решает, что искать, каким источникам доверять, когда переформулировать запрос и когда собрано достаточно доказательств. Агент обязан читать quality_label и warnings.

Конфигурация

Переменная окружения

По умолчанию

Назначение

DSH_BING_SEARCH_URL

https://www.bing.com/search

Переопределяет HTML-эндпоинт Bing, только если задано нестандартное значение (тесты). В противном случае хост выбирается по языку

DSH_WEB_IMPERSONATE

chrome

Отпечаток браузера curl_cffi

DSH_WEB_PROXY

пусто

HTTP/HTTPS/SOCKS-прокси. Процесс использует trust_env=False и не наследует HTTP_PROXY

DSH_WEB_TIMEOUT_SECONDS

20

Таймаут передачи

DSH_WEB_CONNECT_TIMEOUT_SECONDS

8

Таймаут соединения

DSH_WEB_MAX_BODY_BYTES

5242880

Максимальный размер тела для open

DSH_BING_MAX_BODY_BYTES

2097152

Максимальный размер тела страницы поиска

DSH_WEB_MAX_REDIRECTS

8

Максимальное количество редиректов

DSH_WEB_CONCURRENCY

8

Максимальное количество одновременных запросов в процессе

DSH_BING_CACHE_TTL_SECONDS

90

TTL кэша поиска

DSH_WEB_CACHE_TTL_SECONDS

600

TTL кэша страниц

Тесты

Офлайн-тесты (парсеры, оценка качества, маршрутизация по локали, DDG-first / запасной вариант Bing):

uv run pytest -m "not live"

Живой смоук-тест:

RUN_LIVE_BING=1 uv run pytest -m live -s

Имя маркера по-прежнему live / RUN_LIVE_BING. Живой запуск сначала обращается к DDG и использует Bing только в том случае, если DDG недоступен.

CI покрывает Python 3.10, 3.12, 3.13 и 3.14.

Замечания по дизайну и безопасности

Это неофициальный адаптер DuckDuckGo HTML + Bing HTML. Он не использует снятый с поддержки Bing Search API.

  • Разметка DDG находится в src/dsh_bing_search/providers/ddg.py.

  • Разметка Bing находится в src/dsh_bing_search/providers/bing_parser.py.

  • Оценка качества находится в src/dsh_bing_search/quality.py и не зависит от движка.

  • Запросы используют curl_cffi.AsyncSession с имитацией браузера.

  • URL-адреса страниц, предоставленные пользователем, ограничены публичными HTTP(S)-целями и включена безопасная обработка редиректов.

  • Тела ответов ограничены по размеру.

  • Страницы CAPTCHA / challenge / HTTP 202 сообщаются как status="blocked"; плагин не пытается их обходить.

  • Headless Bing на www.bing.com часто возвращает структурно валидные, но нерелевантные карточки. cn.bing.com помогает с некоторыми горячими китайскими запросами; длиннохвостовые имена и заголовки всё ещё могут схлопываться до первого токена. Именно для этого нужна оценка качества.

  • open не выполняет автоматические повторные попытки для медленных целевых сайтов; при необходимости увеличьте переменные окружения таймаута.

Сообщество

DeepSeek Harness в настоящее время находится в предварительной версии для разработчиков, поэтому интерфейсы плагинов могут ещё меняться. Для поддержки и поиска по DSH:

  • Просмотрите тему dsh-plugin.

  • См. репозиторий DeepSeek Harness.

  • Присоединяйтесь к каналам сообщества DSH, ссылки на которые есть в официальном репозитории.

Приветствуются вклады и исправления парсеров.

Лицензия

MIT

Available Tools

4 tools
findFind in Web PageA

Find a literal phrase in a page and return compact context windows around matches.

ParametersJSON Schema
NameRequiredDescriptionDefault
urlYes
patternYes
max_matchesNo
context_charsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
urlYes
errorNo
statusYes
matchesNo
patternYes
source_idNo
total_matchesNo

TDQS

A3.6/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the behavioral disclosure burden. It does reveal key behavior: matching is literal rather than regex or semantic, and the response consists of compact context windows around matches. However, it does not mention case sensitivity, failure modes, page loading behavior, or limits, leaving notable gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single sentence contains the core action, the matching mode, and the response shape with no redundant words. It is front-loaded and easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description is adequate for a simple tool, and the output schema likely covers return values. But with no annotations and no parameter documentation, it lacks details about max_matches behavior, exact context window semantics, and when to prefer sibling tools. It is minimally sufficient but not fully complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It clarifies that 'pattern' is a literal phrase and 'context_chars' relates to compact context windows, but it does not explain 'max_matches', 'url', defaults, or the exact relationship between parameters and output. This is only partial compensation for the missing schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb and resource: finding a literal phrase in a page and returning compact context windows around matches. The word 'literal' helps distinguish it from the sibling 'search' tool, which implies broader or semantic search. This is a clear, specific purpose statement.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage: use this tool when an exact literal phrase is needed within a page. However, it does not explicitly say when not to use it or mention alternatives like 'search' or 'search_images'. The usage guidance is present only by implication.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

openOpen Web PageA

Fetch a public HTTP(S) page with curl_cffi and return cleaned readable text.

Use after search when result snippets are insufficient. Private/local addresses are rejected, redirect targets use curl_cffi safe-follow mode, and response bytes are capped.

ParametersJSON Schema
NameRequiredDescriptionDefault
urlYes
max_charsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
textNo
errorNo
titleNo
statusYes
final_urlNo
source_idNo
truncatedNo
elapsed_msNo
content_typeNo
fetched_bytesNo
requested_urlYes

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the behavioral burden and discloses several useful traits: public-only access, rejection of private/local addresses, safe-follow redirect mode, and a response byte cap. It could also mention error behavior or timeout handling, but the provided constraints are substantial.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two tight sentences front-load the purpose, then add usage context and behavioral constraints. No filler, every sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool is simple and the description covers URL type, output format, redirect behavior, and a cap. The main gap is max_chars semantics, which matters because there is no schema-level documentation and no annotations.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds that URL must be public HTTP(S), but it never explains the max_chars parameter or how the response cap relates to it. An agent cannot confidently tune max_chars based on this text.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb ('Fetch'), resource ('public HTTP(S) page'), and output ('cleaned readable text'). This distinguishes it from siblings like search and search_images: it retrieves page content rather than result snippets or images.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly says 'Use after search when result snippets are insufficient,' giving a clear trigger condition and relationship to the primary sibling. It also states a when-not: private/local addresses are rejected.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_imagesSearch ImagesA

Search image indexes and rank results with pure text so vision is not required.

auto (default) tries Bing Images first and falls back to Wikimedia Commons when the top text score is below ~40, so one call yields a ranked set. bing_images parses Bing Images metadata (original URL / thumbnail / source page / title). commons queries Wikimedia Commons, a curated and licence-clear platform. Every result carries a 0-100 text score, a domain hint and explainable signals; pick the highest score, treat scores below ~40 as unverified, and optionally verify with find/open on the source page before downloading.

Args: query: What the image should depict. Compact concrete nouns plus the qualifier that uniquely identifies the subject (e.g. "复旦光华楼", "台州城墙"). "复旦光华楼" is better than "光华楼". Do not write whole sentences. If a compact query is still ambiguous or hits the wrong entity, write more (place, institution, year, type). count: Number of ranked image results to return, from 1 to 20. market: Locale such as en-US or zh-CN (Bing Images; Commons is language-neutral). provider: auto (default), bing_images, or commons.

ParametersJSON Schema
NameRequiredDescriptionDefault
countNo
queryYes
marketNoen-US
providerNoauto

Output Schema

ParametersJSON Schema
NameRequiredDescription
errorNo
queryYes
marketNo
statusYes
resultsNo
providerNo
warningsNo
elapsed_msNo
returned_countNo
requested_countNo

TDQS

A4.7/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden, and it does so thoroughly. It discloses the ranking mechanism, the auto fallback threshold, what each provider does, and the exact result signals: 0-100 text score, domain hint, and explainable signals. It even tells the agent how to assess confidence and when verification is needed, which goes well beyond a minimal tool description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with purpose and behavior, and the Args section is logically organized. It is longer than typical descriptions, but that length is justified by the zero-coverage schema and the need to explain provider behavior and scoring. Minor redundancy exists because provider defaults and enum values are repeated from the schema, but the added context still earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's provider-switching complexity, fallback threshold, scoring semantics, and four parameters, the description provides everything needed to select and invoke it correctly. It explains query formulation, ranking confidence, provider differences, and optional verification workflow. The output schema covers return structure, so the description does not need to detail the exact JSON response.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must fully compensate for the schema's lack of parameter documentation. It does: `query` has concrete examples and wording advice ('复旦光华楼' is better than '光华楼'), `count` is bounded 1-20, `market` is explained as locale-specific to Bing while Commons is language-neutral, and `provider` enumerates the options. This is excellent parameter documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb and resource: 'Search image indexes and rank results with pure text so vision is not required.' This clearly distinguishes the tool from the sibling `search`, `open`, and `find` by emphasizing image indexes and text-based ranking. The provider variants (bing_images, commons) further specify exactly what kind of image search this is.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives usable routing guidance: `auto` is the default, it falls back to Commons below ~40 text score, and results below ~40 should be treated as unverified. It also recommends verifying with `find`/`open` before downloading, which indirectly differentiates this search tool from sibling file/URL tools. It lacks an explicit 'when not to use this tool' statement, but the behavioral and provider guidance is clear enough.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 4 tool updatesv0.1.0
    • First observedfind
    • First observedopen
    • First observedsearch
    • First observedsearch_images

TDQS

A4.3/5.0

Scored across 4 tools

Disambiguation5/5

Each tool targets a clearly distinct action: web search, image search, page retrieval, and in-page phrase matching. Search and search_images are separated by media type, while open and find both operate on pages but serve complementary pre- and post-retrieval needs, so an agent can select without confusion.

Naming Consistency5/5

All tool names are short imperative verbs in snake_case: search, search_images, open, find. The only compound name, search_images, naturally follows a verb_noun pattern, and the overall naming is predictable and consistent.

Tool Count5/5

Four tools form a tightly scoped search-and-browse toolset. Each tool earns its place: web search, image search, full-page reading, and targeted phrase lookup. The count is neither thin nor bloated for the server's stated purpose.

Completeness5/5

The server covers the full core workflow: discovering content via web or image search, opening pages when snippets are insufficient, and locating specific phrases within pages. Pagination, locale, safesearch, and provider fallback options also cover important search variations, leaving no obvious dead ends.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    MCP server for web search and content extraction using DuckDuckGo or SearXNG, with Playwright-based fetching and LLM-powered data extraction.
    140
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    MCP server for internet search via direct Google and DuckDuckGo HTML scraping with AI-powered result normalization and optional summarization, requiring no API keys for search.
    MIT