-
Notifications
You must be signed in to change notification settings - Fork 18
feat: add OAuth URL generation tool #211
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 all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
cc74f51
feat: add OAuth URL generation tool for component configurations
AdamVyborny c452d65
fix: resolve linting issues in OAuth tool
AdamVyborny 830a85a
chore: remove CLAUDE.md development guide
AdamVyborny f135aa5
fix: tool description
AdamVyborny 40047f6
refactor: encapsulate token creation in client method
AdamVyborny 20d1f70
fix: make OAuth tool description more clear
AdamVyborny 3964116
refactor: use KeboolaClient.from_state in OAuth tests
AdamVyborny e765fa8
fix: remove duplicated line
AdamVyborny bc864fa
bump version
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
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,64 @@ | ||
"""OAuth URL generation tools for the MCP server.""" | ||
|
||
import logging | ||
from typing import Annotated | ||
|
||
from fastmcp import Context | ||
from fastmcp.tools import FunctionTool | ||
from pydantic import Field | ||
|
||
from keboola_mcp_server.client import KeboolaClient | ||
from keboola_mcp_server.errors import tool_errors | ||
from keboola_mcp_server.mcp import KeboolaMcpServer, with_session_state | ||
|
||
LOG = logging.getLogger(__name__) | ||
|
||
TOOL_GROUP_NAME = 'OAUTH' | ||
|
||
|
||
def add_oauth_tools(mcp: KeboolaMcpServer) -> None: | ||
"""Adds OAuth tools to the MCP server.""" | ||
mcp.add_tool(FunctionTool.from_function(create_oauth_url)) | ||
LOG.info('OAuth tools added to the MCP server.') | ||
|
||
|
||
@tool_errors() | ||
@with_session_state() | ||
async def create_oauth_url( | ||
component_id: Annotated[ | ||
str, Field(description='The component ID to grant access to (e.g., "keboola.ex-google-analytics-v4").') | ||
], | ||
config_id: Annotated[str, Field(description='The configuration ID for the component.')], | ||
ctx: Context, | ||
) -> str: | ||
""" | ||
Generates an OAuth authorization URL for a Keboola component configuration. | ||
|
||
When using this tool, be very concise in your response. Just guide the user to click the | ||
authorization link. | ||
|
||
Note that this tool should be called specifically for the OAuth-requiring components after their | ||
configuration is created e.g. keboola.ex-google-analytics-v4 and keboola.ex-gmail. | ||
""" | ||
client = KeboolaClient.from_state(ctx.session.state) | ||
|
||
# Create the token using the storage client | ||
token_response = await client.storage_client.token_create( | ||
description=f'Short-lived token for OAuth URL - {component_id}/{config_id}', | ||
component_access=[component_id], | ||
expires_in=3600, # 1 hour expiration | ||
) | ||
|
||
# Extract the token from response | ||
sapi_token = token_response['token'] | ||
|
||
# Get the storage API URL from client | ||
storage_api_url = client.storage_client.base_api_url | ||
|
||
# Generate OAuth URL | ||
oauth_url = ( | ||
f'https://external.keboola.com/oauth/index.html?token={sapi_token}' | ||
f'&sapiUrl={storage_api_url}#/{component_id}/{config_id}' | ||
) | ||
|
||
return oauth_url |
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
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,121 @@ | ||
"""Tests for OAuth URL generation tools.""" | ||
|
||
from typing import Any, Mapping | ||
|
||
import pytest | ||
from mcp.server.fastmcp import Context | ||
|
||
from keboola_mcp_server.client import KeboolaClient | ||
from keboola_mcp_server.tools.oauth import create_oauth_url | ||
|
||
|
||
@pytest.fixture | ||
def mock_token_response() -> Mapping[str, Any]: | ||
"""Mock valid response from the token creation endpoint.""" | ||
return { | ||
'token': 'KBC_TOKEN_12345', | ||
'description': 'Short-lived token for OAuth URL - keboola.ex-google-analytics-v4/config-123', | ||
'expiresIn': 3600, | ||
} | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_create_oauth_url_success( | ||
mcp_context_client: Context, mock_token_response: Mapping[str, Any] | ||
) -> None: | ||
"""Test successful OAuth URL creation.""" | ||
# Mock the storage client's token_create method to return the token response | ||
keboola_client = KeboolaClient.from_state(mcp_context_client.session.state) | ||
keboola_client.storage_client.token_create.return_value = mock_token_response | ||
keboola_client.storage_client.base_api_url = 'https://connection.test.keboola.com' | ||
|
||
component_id = 'keboola.ex-google-analytics-v4' | ||
config_id = 'config-123' | ||
|
||
result = await create_oauth_url(component_id=component_id, config_id=config_id, ctx=mcp_context_client) | ||
|
||
# Verify the storage client was called with correct parameters | ||
keboola_client.storage_client.token_create.assert_called_once_with( | ||
description=f'Short-lived token for OAuth URL - {component_id}/{config_id}', | ||
component_access=[component_id], | ||
expires_in=3600, | ||
) | ||
|
||
# Verify the response is the URL string | ||
assert isinstance(result, str) | ||
|
||
expected_url = ( | ||
f'https://external.keboola.com/oauth/index.html' | ||
f'?token=KBC_TOKEN_12345' | ||
f'&sapiUrl=https://connection.test.keboola.com' | ||
f'#/{component_id}/{config_id}' | ||
) | ||
assert result == expected_url | ||
|
||
|
||
@pytest.mark.asyncio | ||
@pytest.mark.parametrize( | ||
('component_id', 'config_id'), | ||
[ | ||
('keboola.ex-google-analytics-v4', 'my-config-123'), | ||
('keboola.ex-gmail', 'gmail-config-456'), | ||
('other.component', 'test-config'), | ||
], | ||
) | ||
async def test_create_oauth_url_different_components( | ||
mcp_context_client: Context, | ||
mock_token_response: Mapping[str, Any], | ||
component_id: str, | ||
config_id: str, | ||
) -> None: | ||
"""Test OAuth URL creation for different components.""" | ||
# Mock the storage client | ||
keboola_client = KeboolaClient.from_state(mcp_context_client.session.state) | ||
keboola_client.storage_client.token_create.return_value = mock_token_response | ||
keboola_client.storage_client.base_api_url = 'https://connection.test.keboola.com' | ||
|
||
result = await create_oauth_url(component_id=component_id, config_id=config_id, ctx=mcp_context_client) | ||
|
||
# Verify component-specific parameters were used | ||
assert isinstance(result, str) | ||
assert f'#/{component_id}/{config_id}' in result | ||
|
||
# Verify the API call included the correct component access | ||
call_args = keboola_client.storage_client.token_create.call_args | ||
assert call_args[1]['component_access'] == [component_id] | ||
assert component_id in call_args[1]['description'] | ||
assert config_id in call_args[1]['description'] | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_create_oauth_url_token_creation_failure( | ||
mcp_context_client: Context, | ||
) -> None: | ||
"""Test OAuth URL creation when token creation fails.""" | ||
# Mock the storage client to raise an exception | ||
keboola_client = KeboolaClient.from_state(mcp_context_client.session.state) | ||
keboola_client.storage_client.token_create.side_effect = Exception( | ||
'Token creation failed' | ||
) | ||
|
||
with pytest.raises(Exception, match='Token creation failed'): | ||
await create_oauth_url( | ||
component_id='keboola.ex-google-analytics-v4', config_id='config-123', ctx=mcp_context_client | ||
) | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_create_oauth_url_missing_token_in_response(mcp_context_client: Context) -> None: | ||
"""Test OAuth URL creation when token is missing from response.""" | ||
# Mock response without token field | ||
invalid_response = { | ||
'description': 'Short-lived token for OAuth URL', | ||
'expiresIn': 3600, | ||
} | ||
keboola_client = KeboolaClient.from_state(mcp_context_client.session.state) | ||
keboola_client.storage_client.token_create.return_value = invalid_response | ||
|
||
with pytest.raises(KeyError): | ||
await create_oauth_url( | ||
component_id='keboola.ex-google-analytics-v4', config_id='config-123', ctx=mcp_context_client | ||
) |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that the query part parameters should be properly encoded by using urllib.parse.urlencode function and the whole URL should be constructed using urllib.parse.urlunsplit function.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I will look into it and fix in follow-up PR. Thanks.