-
Notifications
You must be signed in to change notification settings - Fork 317
support loading text prompts #12
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e4cb306
feat(prompts): support loading txt & img prompts
mr-brobot 48825bb
fix(pyproject): include missing changes
mr-brobot b3a1725
fix(prompts): optional mcp args
mr-brobot 30ba5e3
feat(prompts): pr feedback
mr-brobot 4067d3c
chore: fmt
mr-brobot 73fb1e9
fix(prompts): exception types
mr-brobot 0cd2ede
Merge branch 'main' into feat/prompts
vbarda ce583ee
update
vbarda File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| from typing import Any, Optional, Union | ||
|
|
||
| from langchain_core.messages import AIMessage, HumanMessage | ||
| from mcp import ClientSession | ||
| from mcp.types import PromptMessage | ||
|
|
||
|
|
||
| class UnsupportedContentError(Exception): | ||
| """Raised when a prompt message contains unsupported content.""" | ||
|
|
||
| pass | ||
|
|
||
|
|
||
| class UnsupportedRoleError(Exception): | ||
| """Raised when a prompt message contains an unsupported role.""" | ||
|
|
||
| pass | ||
|
|
||
|
|
||
| def convert_mcp_prompt_message_to_langchain_message( | ||
| message: PromptMessage, | ||
| ) -> Union[HumanMessage, AIMessage]: | ||
| """Convert an MCP prompt message to a LangChain message. | ||
|
|
||
| Args: | ||
| message: MCP prompt message to convert | ||
|
|
||
| Returns: | ||
| a LangChain message | ||
| """ | ||
| if message.content.type == "text": | ||
| if message.role == "user": | ||
| return HumanMessage(content=message.content.text) | ||
| elif message.role == "assistant": | ||
| return AIMessage(content=message.content.text) | ||
| else: | ||
| raise UnsupportedRoleError(f"Unsupported prompt message role: {message.role}") | ||
|
|
||
| raise UnsupportedContentError( | ||
| f"Unsupported prompt message content type: {message.content.type}" | ||
| ) | ||
|
|
||
|
|
||
| async def load_mcp_prompt( | ||
| session: ClientSession, name: str, arguments: Optional[dict[str, Any]] = None | ||
| ) -> list[Union[HumanMessage, AIMessage]]: | ||
| """Load MCP prompt and convert to LangChain messages.""" | ||
| response = await session.get_prompt(name, arguments) | ||
| return [ | ||
| convert_mcp_prompt_message_to_langchain_message(message) for message in response.messages | ||
| ] | ||
vbarda marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,30 +7,26 @@ name = "langchain-mcp-adapters" | |
| version = "0.0.3" | ||
| description = "Make Anthropic Model Context Protocol (MCP) tools compatible with LangChain and LangGraph agents." | ||
| authors = [ | ||
| {name = "Vadym Barda", email = "[email protected] "} | ||
| { name = "Vadym Barda", email = "[email protected] " }, | ||
| ] | ||
| readme = "README.md" | ||
| requires-python = ">=3.10" | ||
| dependencies = [ | ||
| "langchain-core>=0.3.36", | ||
| "mcp>=1.2.1", | ||
| ] | ||
| dependencies = ["langchain-core>=0.3.36", "mcp>=1.2.1"] | ||
|
|
||
| [dependency-groups] | ||
| test = [ | ||
| "pytest>=8.0.0", | ||
| "ruff>=0.9.4", | ||
| "mypy>=1.8.0", | ||
| "pytest-socket>=0.7.0", | ||
| "pytest-asyncio>=0.25.0", | ||
| "types-setuptools>=69.0.0", | ||
| ] | ||
|
|
||
| [tool.pytest.ini_options] | ||
| minversion = "8.0" | ||
| addopts = "-ra -q -v" | ||
| testpaths = [ | ||
| "tests", | ||
| ] | ||
| testpaths = ["tests"] | ||
| python_files = ["test_*.py"] | ||
| python_functions = ["test_*"] | ||
|
|
||
|
|
@@ -40,14 +36,14 @@ target-version = "py310" | |
|
|
||
| [tool.ruff.lint] | ||
| select = [ | ||
| "E", # pycodestyle errors | ||
| "W", # pycodestyle warnings | ||
| "F", # pyflakes | ||
| "I", # isort | ||
| "B", # flake8-bugbear | ||
| "E", # pycodestyle errors | ||
| "W", # pycodestyle warnings | ||
| "F", # pyflakes | ||
| "I", # isort | ||
| "B", # flake8-bugbear | ||
| ] | ||
| ignore = [ | ||
| "E501" # line-length | ||
| "E501", # line-length | ||
| ] | ||
|
|
||
|
|
||
|
|
@@ -57,4 +53,3 @@ warn_return_any = true | |
| warn_unused_configs = true | ||
| disallow_untyped_defs = true | ||
| check_untyped_defs = true | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| def test_import() -> None: | ||
| """Test that the code can be imported""" | ||
| from langchain_mcp_adapters import client, tools # noqa: F401 | ||
| from langchain_mcp_adapters import client, prompts, tools # noqa: F401 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import pytest | ||
| from langchain_core.messages import AIMessage, HumanMessage | ||
| from mcp.types import ( | ||
| EmbeddedResource, | ||
| ImageContent, | ||
| PromptMessage, | ||
| TextContent, | ||
| TextResourceContents, | ||
| ) | ||
|
|
||
| from langchain_mcp_adapters.prompts import ( | ||
| UnsupportedContentError, | ||
| convert_mcp_prompt_message_to_langchain_message, | ||
| load_mcp_prompt, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "role,text,expected_cls", | ||
| [ | ||
| ("assistant", "Hello", AIMessage), | ||
| ("user", "Hello", HumanMessage), | ||
| ], | ||
| ) | ||
| def test_convert_mcp_prompt_message_to_langchain_message_with_text_content( | ||
| role: str, text: str, expected_cls: type | ||
| ): | ||
| message = PromptMessage(role=role, content=TextContent(type="text", text=text)) | ||
| result = convert_mcp_prompt_message_to_langchain_message(message) | ||
| assert isinstance(result, expected_cls) | ||
| assert result.content == text | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("role", ["assistant", "user"]) | ||
| def test_convert_mcp_prompt_message_to_langchain_message_with_resource_content(role: str): | ||
| message = PromptMessage( | ||
| role=role, | ||
| content=EmbeddedResource( | ||
| type="resource", | ||
| resource=TextResourceContents( | ||
| uri="message://greeting", mimeType="text/plain", text="hi" | ||
| ), | ||
| ), | ||
| ) | ||
| with pytest.raises(UnsupportedContentError): | ||
| convert_mcp_prompt_message_to_langchain_message(message) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("role", ["assistant", "user"]) | ||
| def test_convert_mcp_prompt_message_to_langchain_message_with_image_content(role: str): | ||
| message = PromptMessage( | ||
| role=role, content=ImageContent(type="image", mimeType="image/png", data="base64data") | ||
| ) | ||
| with pytest.raises(UnsupportedContentError): | ||
| convert_mcp_prompt_message_to_langchain_message(message) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_load_mcp_prompt(): | ||
| session = AsyncMock() | ||
| session.get_prompt = AsyncMock( | ||
| return_value=AsyncMock( | ||
| messages=[ | ||
| PromptMessage(role="user", content=TextContent(type="text", text="Hello")), | ||
| PromptMessage(role="assistant", content=TextContent(type="text", text="Hi")), | ||
| ] | ||
| ) | ||
| ) | ||
| result = await load_mcp_prompt(session, "test_prompt") | ||
| assert len(result) == 2 | ||
| assert isinstance(result[0], HumanMessage) | ||
| assert result[0].content == "Hello" | ||
| assert isinstance(result[1], AIMessage) | ||
| assert result[1].content == "Hi" |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.