-
Notifications
You must be signed in to change notification settings - Fork 30
refactor: move transport logic to a ToolboxTransport class #344
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
Open
twishabansal
wants to merge
27
commits into
main
Choose a base branch
from
mcp-restructure
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
04f7962
add basic code
twishabansal 9ba5bbc
fixes
twishabansal 34cb50a
test fix
twishabansal ea417ba
new unit tests
twishabansal aa356b1
Merge branch 'main' into mcp-restructure
twishabansal 7c0f917
rename ToolboxTransport
twishabansal 434e91d
add py3.9 support
twishabansal 31d0f9e
fix langchain tool tests
twishabansal b50513b
test fix
twishabansal c222d25
lint
twishabansal b244740
fix tests
twishabansal 4b0f561
Merge branch 'main' into mcp-restructure
twishabansal d93f4dd
move manage session into transport
twishabansal f9d8e64
move warning to diff file
twishabansal d6361ed
avoid code duplication
twishabansal 0f3bacc
fix tests
twishabansal 0a79f5a
lint
twishabansal fcf7da3
remove redundant tests
twishabansal c65a94a
make invoke method return str
twishabansal e2269f8
lint
twishabansal 25802e2
fix return type
twishabansal d41aed8
small refactor
twishabansal 31809a1
rename private method
twishabansal 09866c4
Merge branch 'main' into mcp-restructure
twishabansal c7455a8
Merge branch 'main' into mcp-restructure
twishabansal f43909e
fix tests
twishabansal f07d4b3
lint
twishabansal 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,58 @@ | ||
# Copyright 2025 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from abc import ABC, abstractmethod | ||
from typing import Mapping, Optional | ||
|
||
from .protocol import ManifestSchema | ||
|
||
|
||
class ITransport(ABC): | ||
"""Defines the contract for a 'smart' transport that handles both | ||
protocol formatting and network communication. | ||
""" | ||
|
||
@property | ||
@abstractmethod | ||
def base_url(self) -> str: | ||
"""The base URL for the transport.""" | ||
pass | ||
|
||
@abstractmethod | ||
async def tool_get( | ||
self, tool_name: str, headers: Optional[Mapping[str, str]] = None | ||
) -> ManifestSchema: | ||
"""Gets a single tool from the server.""" | ||
pass | ||
|
||
@abstractmethod | ||
async def tools_list( | ||
self, | ||
toolset_name: Optional[str] = None, | ||
headers: Optional[Mapping[str, str]] = None, | ||
) -> ManifestSchema: | ||
"""Lists available tools from the server.""" | ||
pass | ||
|
||
@abstractmethod | ||
async def tool_invoke( | ||
self, tool_name: str, arguments: dict, headers: Mapping[str, str] | ||
) -> str: | ||
"""Invokes a specific tool on the server.""" | ||
pass | ||
|
||
@abstractmethod | ||
async def close(self): | ||
"""Closes any underlying connections.""" | ||
pass |
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
95 changes: 95 additions & 0 deletions
95
packages/toolbox-core/src/toolbox_core/toolbox_transport.py
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,95 @@ | ||
# Copyright 2025 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from typing import Mapping, Optional | ||
from warnings import warn | ||
|
||
from aiohttp import ClientSession | ||
|
||
from .itransport import ITransport | ||
from .protocol import ManifestSchema | ||
|
||
|
||
class ToolboxTransport(ITransport): | ||
"""Transport for the native Toolbox protocol.""" | ||
|
||
def __init__(self, base_url: str, session: Optional[ClientSession]): | ||
self.__base_url = base_url | ||
|
||
# If no aiohttp.ClientSession is provided, make our own | ||
self.__manage_session = False | ||
if session is not None: | ||
self.__session = session | ||
else: | ||
self.__manage_session = True | ||
self.__session = ClientSession() | ||
|
||
@property | ||
def base_url(self) -> str: | ||
"""The base URL for the transport.""" | ||
return self.__base_url | ||
|
||
async def __get_manifest( | ||
self, url: str, headers: Optional[Mapping[str, str]] | ||
) -> ManifestSchema: | ||
"""Helper method to perform GET requests and parse the ManifestSchema.""" | ||
async with self.__session.get(url, headers=headers) as response: | ||
if not response.ok: | ||
error_text = await response.text() | ||
raise RuntimeError( | ||
f"API request failed with status {response.status} ({response.reason}). Server response: {error_text}" | ||
) | ||
json = await response.json() | ||
return ManifestSchema(**json) | ||
|
||
async def tool_get( | ||
self, tool_name: str, headers: Optional[Mapping[str, str]] = None | ||
) -> ManifestSchema: | ||
url = f"{self.__base_url}/api/tool/{tool_name}" | ||
return await self.__get_manifest(url, headers) | ||
|
||
async def tools_list( | ||
self, | ||
toolset_name: Optional[str] = None, | ||
headers: Optional[Mapping[str, str]] = None, | ||
) -> ManifestSchema: | ||
url = f"{self.__base_url}/api/toolset/{toolset_name or ''}" | ||
return await self.__get_manifest(url, headers) | ||
|
||
async def tool_invoke( | ||
self, tool_name: str, arguments: dict, headers: Mapping[str, str] | ||
) -> str: | ||
# ID tokens contain sensitive user information (claims). Transmitting | ||
# these over HTTP exposes the data to interception and unauthorized | ||
# access. Always use HTTPS to ensure secure communication and protect | ||
# user privacy. | ||
if self.base_url.startswith("http://") and headers: | ||
warn( | ||
"Sending data token over HTTP. User data may be exposed. Use HTTPS for secure communication." | ||
) | ||
url = f"{self.__base_url}/api/tool/{tool_name}/invoke" | ||
async with self.__session.post( | ||
url, | ||
json=arguments, | ||
headers=headers, | ||
) as resp: | ||
body = await resp.json() | ||
if not resp.ok: | ||
err = body.get("error", f"unexpected status from server: {resp.status}") | ||
raise Exception(err) | ||
return body.get("result") | ||
|
||
async def close(self): | ||
if self.__manage_session and not self.__session.closed: | ||
await self.__session.close() |
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.