Почему webbrowser.open не работает с сервером mcp? [закрыто]Python

Программы на Python
Ответить
Anonymous
 Почему webbrowser.open не работает с сервером mcp? [закрыто]

Сообщение Anonymous »

  • Краткий контекст: Я создаю локальный агент Python с использованием 3B-модели на основе llama.cpp и инструментов в стиле MCP. Один инструмент должен открывать поиск YouTube в браузере.
  • Что работает
  • Инструмент называется
  • URL возвращается правильно.
  • Что не так
  • Код: Выделить всё

    webbrowser.open
    ничего не делает при вызове внутри инструмента/сервера.
  • Среда
  • ОС (например, Ubuntu 24.04)
  • Среда рабочего стола (GNOME/KDE/WSL/headless/etc.)
  • Конкретный вопрос: Плохая ли идея вызывать webbrowser.open изнутри серверного процесса? Должен ли я перенести логику открытия URL-адресов на сторону клиента? Есть какие-нибудь рекомендации для этого при локальной настройке?
  • Код для контекста: Серверный метод для открытия браузера

Код: Выделить всё

        @self.app.tool()
async def open_youtube_search(topic: str) -> str:
"""Return a YouTube search URL for the given topic and *try* to open it."""
logger.debug(f"[TOOL] Searching YouTube for topic: {topic!r}")

query = quote_plus(topic)
url = f"https://www.youtube.com/results?search_query={query}"

try:
browser = web.get()
logger.debug("[TOOL] Using browser handler:", browser)
except web.Error as e:
logger.debug("[TOOL] webbrowser.get() failed:", e)

opened = web.open(url, new=2)

return url
  • Журналы: Я предоставлю журналы, созданные во время разговора.

Код: Выделить всё

[2025-12-16 22:20:22,472] [DEBUG] agent tool required
[12/16/25 22:20:22] INFO     Processing request of type CallToolRequest                                                                                                        server.py:709
[2025-12-16 22:20:22,486] [DEBUG] mcp function(open_youtube_search) with param({'topic': 'Michael Jackson'}) has results([TextContent(type='text', text='https://www.youtube.com/results?search_query=Michael+Jackson', annotations=None, meta=None)])
[2025-12-16 22:20:22,487] [DEBUG] got result of each tool ([{"name": "open_youtube_search", "output": ["https://www.youtube.com/results?search_query=Michael+Jackson"]}])
[2025-12-16 22:20:41,571] [DEBUG] llm generated final response(Here are some popular Michael Jackson videos on YouTube:

1. **"Thriller"** (1983) - a classic music video and one of the most iconic songs of all time.
2. **"Billie Jean"** (1983) - another hit single from the "Thriller" album.
3. **"Beat It"** (1983) - a high-energy music video with a memorable music video.
4. **"Black or White"** (1991) - a socially conscious song with a music video that sparked controversy.
5. **"Man in the Mirror"** (1988) - a powerful song about self-improvement and social change.
6. **"Remember the Time"** (1991) - a fun and upbeat music video with a star-studded cast.
7. **"Don't Stop 'Til You Get Enough"** (1979) - one of Michael's earliest hits, featuring his signature dance moves.
8. **"Heal the World"** (1991) - a song and music video that promoted unity and global understanding.
9. **"Rock with You"** (1979) - a smooth and funky song that showcases Michael's vocal range.
10. **"Moonwalker"** (1988) - a music video that combined music, dance, and special effects.

Which Michael Jackson video would you like to watch?)
(assistant) tool calling [open_youtube_search(topic="Michael Jackson")]
(assistant) tool result [{"name": "open_youtube_search", "output": ["https://www.youtube.com/results?search_query=Michael+Jackson"]}]
(assistant) Here are some popular Michael Jackson videos on YouTube:

1. **"Thriller"** (1983) - a classic music video and one of the most iconic songs of all time.
2. **"Billie Jean"** (1983) - another hit single from the "Thriller" album.
3. **"Beat It"** (1983) - a high-energy music video with a memorable music video.
4.  **"Black or White"** (1991) - a socially conscious song with a music video that sparked controversy.
5. **"Man in the Mirror"** (1988) - a powerful song about self-improvement and social change.
6. **"Remember the Time"** (1991) - a fun and upbeat music video with a star-studded cast.
7. **"Don't Stop 'Til You Get Enough"** (1979) - one of Michael's earliest hits, featuring his signature dance moves.
8. **"Heal the World"** (1991) - a song and music video that promoted unity and global understanding.
9. **"Rock with You"** (1979) - a smooth and funky song that showcases Michael's vocal range.
10. **"Moonwalker"** (1988) - a music video that combined music, dance, and special effects.

Which Michael Jackson video would you like to watch
  • Дополнение: Если мне придется предоставить что-то еще, я буду рад добавить к этому.


Подробнее здесь: https://stackoverflow.com/questions/798 ... mcp-server
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»