mcs-auth-oauth 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcs-auth-oauth
3
+ Version: 0.1.0
4
+ Summary: OAuth 2.0 Authorization Code adapter for the Model Context Standard.
5
+ Author-email: Danny Gerst <danny@dannygerst.de>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://www.modelcontextstandard.io
8
+ Project-URL: Source, https://github.com/modelcontextstandard/python-sdk
9
+ Keywords: mcs,modelcontextstandard,auth,oauth2,authorization-code
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: mcs-auth>=0.1
25
+ Dynamic: license-file
26
+
27
+ # mcs-auth-oauth
28
+
29
+ **Zero-dependency OAuth 2.0 for AI agents.** Authorization Code Flow with
30
+ PKCE for the **Model Context Standard (MCS)**.
31
+
32
+ No `requests`. No `authlib`. No heavyweight SDK. Just the Python standard
33
+ library, a 5-second localhost callback server, and your agent has an OAuth
34
+ token. Works with any OAuth 2.0 provider -- Google, Auth0, Microsoft,
35
+ GitHub, you name it.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install mcs-auth-oauth
41
+ ```
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ from mcs.auth.oauth import OAuthProvider
47
+
48
+ provider = OAuthProvider(
49
+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",
50
+ token_url="https://oauth2.googleapis.com/token",
51
+ client_id="...",
52
+ client_secret="...",
53
+ scopes={"gmail": "https://mail.google.com/"},
54
+ )
55
+
56
+ # Opens browser, user logs in, token returned
57
+ token = provider.get_token("gmail")
58
+ ```
59
+
60
+ ## How it works
61
+
62
+ 1. Agent calls `get_token("gmail")`
63
+ 2. Browser opens with the provider's consent screen
64
+ 3. User logs in and grants access
65
+ 4. Localhost callback receives the authorization code
66
+ 5. Code is exchanged for tokens (with PKCE)
67
+ 6. Token returned to agent -- done
68
+
69
+ The entire flow happens in a single `get_token()` call. The localhost
70
+ server lives for exactly one request and shuts down immediately.
71
+
72
+ ## Use with Auth0 Token Vault
73
+
74
+ ```python
75
+ from mcs.auth.auth0 import Auth0Provider
76
+ from mcs.auth.oauth import OAuthAdapter
77
+
78
+ provider = Auth0Provider(
79
+ domain="my-tenant.auth0.com",
80
+ client_id="...",
81
+ client_secret="...",
82
+ _auth=OAuthAdapter(
83
+ authorize_url="https://my-tenant.auth0.com/authorize",
84
+ token_url="https://my-tenant.auth0.com/oauth/token",
85
+ client_id="...",
86
+ client_secret="...",
87
+ extra_params={"connection": "google-oauth2", "audience": "..."},
88
+ ),
89
+ )
90
+ ```
91
+
92
+ ## Links
93
+
94
+ - **Homepage:** <https://www.modelcontextstandard.io>
95
+ - **Source:** <https://github.com/modelcontextstandard/python-sdk>
96
+
97
+ ## License
98
+
99
+ Apache-2.0
@@ -0,0 +1,73 @@
1
+ # mcs-auth-oauth
2
+
3
+ **Zero-dependency OAuth 2.0 for AI agents.** Authorization Code Flow with
4
+ PKCE for the **Model Context Standard (MCS)**.
5
+
6
+ No `requests`. No `authlib`. No heavyweight SDK. Just the Python standard
7
+ library, a 5-second localhost callback server, and your agent has an OAuth
8
+ token. Works with any OAuth 2.0 provider -- Google, Auth0, Microsoft,
9
+ GitHub, you name it.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install mcs-auth-oauth
15
+ ```
16
+
17
+ ## Quick start
18
+
19
+ ```python
20
+ from mcs.auth.oauth import OAuthProvider
21
+
22
+ provider = OAuthProvider(
23
+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",
24
+ token_url="https://oauth2.googleapis.com/token",
25
+ client_id="...",
26
+ client_secret="...",
27
+ scopes={"gmail": "https://mail.google.com/"},
28
+ )
29
+
30
+ # Opens browser, user logs in, token returned
31
+ token = provider.get_token("gmail")
32
+ ```
33
+
34
+ ## How it works
35
+
36
+ 1. Agent calls `get_token("gmail")`
37
+ 2. Browser opens with the provider's consent screen
38
+ 3. User logs in and grants access
39
+ 4. Localhost callback receives the authorization code
40
+ 5. Code is exchanged for tokens (with PKCE)
41
+ 6. Token returned to agent -- done
42
+
43
+ The entire flow happens in a single `get_token()` call. The localhost
44
+ server lives for exactly one request and shuts down immediately.
45
+
46
+ ## Use with Auth0 Token Vault
47
+
48
+ ```python
49
+ from mcs.auth.auth0 import Auth0Provider
50
+ from mcs.auth.oauth import OAuthAdapter
51
+
52
+ provider = Auth0Provider(
53
+ domain="my-tenant.auth0.com",
54
+ client_id="...",
55
+ client_secret="...",
56
+ _auth=OAuthAdapter(
57
+ authorize_url="https://my-tenant.auth0.com/authorize",
58
+ token_url="https://my-tenant.auth0.com/oauth/token",
59
+ client_id="...",
60
+ client_secret="...",
61
+ extra_params={"connection": "google-oauth2", "audience": "..."},
62
+ ),
63
+ )
64
+ ```
65
+
66
+ ## Links
67
+
68
+ - **Homepage:** <https://www.modelcontextstandard.io>
69
+ - **Source:** <https://github.com/modelcontextstandard/python-sdk>
70
+
71
+ ## License
72
+
73
+ Apache-2.0
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=63", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mcs-auth-oauth"
7
+ version = "0.1.0"
8
+ description = "OAuth 2.0 Authorization Code adapter for the Model Context Standard."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ keywords = ["mcs", "modelcontextstandard", "auth", "oauth2", "authorization-code"]
13
+ authors = [{ name = "Danny Gerst", email = "danny@dannygerst.de" }]
14
+ license-files = ["LICENSE"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.9",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Security",
25
+ "Topic :: Software Development :: Libraries",
26
+ "Typing :: Typed",
27
+ ]
28
+
29
+ urls = {"Homepage" = "https://www.modelcontextstandard.io", "Source" = "https://github.com/modelcontextstandard/python-sdk"}
30
+
31
+ dependencies = [
32
+ "mcs-auth>=0.1",
33
+ ]
34
+
35
+ [tool.uv.sources]
36
+ mcs-auth = { workspace = true }
37
+
38
+ [tool.setuptools.packages.find]
39
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """OAuth 2.0 Authorization Code adapter and provider for MCS."""
2
+
3
+ from .oauth_adapter import OAuthAdapter
4
+ from .oauth_provider import OAuthProvider
5
+
6
+ __all__ = ["OAuthAdapter", "OAuthProvider"]
@@ -0,0 +1,201 @@
1
+ """OAuth 2.0 Authorization Code Flow adapter for MCS.
2
+
3
+ Implements ``AuthPort`` using the standard Authorization Code Flow with
4
+ PKCE (RFC 7636). Spins up a temporary local HTTP server to receive the
5
+ callback, opens the user's browser, exchanges the code for tokens, and
6
+ returns the result.
7
+
8
+ This adapter uses only the Python standard library -- no external
9
+ dependencies beyond ``mcs-auth``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import http.server
16
+ import json
17
+ import secrets
18
+ import urllib.parse
19
+ import urllib.request
20
+ import webbrowser
21
+ from base64 import urlsafe_b64encode
22
+ from typing import Any
23
+
24
+ class OAuthAdapter:
25
+ """Auth transport adapter that performs OAuth 2.0 Authorization Code Flow.
26
+
27
+ Satisfies ``AuthPort.authenticate(scope) -> str``.
28
+
29
+ Parameters
30
+ ----------
31
+ authorize_url :
32
+ Provider's authorization endpoint
33
+ (e.g. ``"https://accounts.google.com/o/oauth2/v2/auth"``).
34
+ token_url :
35
+ Provider's token endpoint
36
+ (e.g. ``"https://oauth2.googleapis.com/token"``).
37
+ client_id :
38
+ OAuth client ID.
39
+ client_secret :
40
+ OAuth client secret (empty string for public clients with PKCE).
41
+ scopes :
42
+ OAuth scopes to request. Can be a dict mapping MCS scope names
43
+ to OAuth scope strings, or a single string applied to all scopes.
44
+ callback_port :
45
+ Local port for the redirect callback (default 3000).
46
+ callback_path :
47
+ Path on the local server for the callback (default ``"/callback"``).
48
+ extra_params :
49
+ Extra query params to include in the authorization URL
50
+ (e.g. ``{"connection": "google-oauth2"}`` for Auth0).
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ *,
56
+ authorize_url: str,
57
+ token_url: str,
58
+ client_id: str,
59
+ client_secret: str = "",
60
+ scopes: dict[str, str] | str = "",
61
+ callback_port: int = 3000,
62
+ callback_path: str = "/callback",
63
+ extra_params: dict[str, str] | None = None,
64
+ on_auth_start: Any | None = None,
65
+ ) -> None:
66
+ self._authorize_url = authorize_url
67
+ self._token_url = token_url
68
+ self._client_id = client_id
69
+ self._client_secret = client_secret
70
+ self._scopes = scopes
71
+ self._callback_port = callback_port
72
+ self._callback_path = callback_path
73
+ self._extra_params = extra_params or {}
74
+ self._on_auth_start = on_auth_start
75
+
76
+ # Cache: scope → token dict
77
+ self._tokens: dict[str, dict[str, Any]] = {}
78
+
79
+ def authenticate(self, scope: str) -> str:
80
+ """Run OAuth Authorization Code Flow and return the token.
81
+
82
+ Opens a browser window for the user to log in, blocks until
83
+ the callback is received, then returns the token.
84
+
85
+ Returns the ``refresh_token`` if available, otherwise the
86
+ ``access_token``.
87
+ """
88
+ if scope in self._tokens:
89
+ tokens = self._tokens[scope]
90
+ return tokens.get("refresh_token", tokens["access_token"])
91
+
92
+ if self._on_auth_start:
93
+ self._on_auth_start(scope)
94
+
95
+ # Resolve OAuth scopes
96
+ if isinstance(self._scopes, dict):
97
+ oauth_scope = self._scopes.get(scope, "openid email offline_access")
98
+ else:
99
+ oauth_scope = self._scopes or "openid email offline_access"
100
+
101
+ # PKCE (RFC 7636)
102
+ code_verifier = secrets.token_urlsafe(64)
103
+ code_challenge = urlsafe_b64encode(
104
+ hashlib.sha256(code_verifier.encode()).digest()
105
+ ).rstrip(b"=").decode()
106
+
107
+ redirect_uri = f"http://localhost:{self._callback_port}{self._callback_path}"
108
+ state = secrets.token_urlsafe(16)
109
+
110
+ # Build authorization URL
111
+ params: dict[str, str] = {
112
+ "response_type": "code",
113
+ "client_id": self._client_id,
114
+ "redirect_uri": redirect_uri,
115
+ "scope": oauth_scope,
116
+ "state": state,
117
+ "code_challenge": code_challenge,
118
+ "code_challenge_method": "S256",
119
+ **self._extra_params,
120
+ }
121
+ auth_url = f"{self._authorize_url}?{urllib.parse.urlencode(params)}"
122
+
123
+ # Start callback server and open browser
124
+ code = self._run_callback_server(auth_url, state)
125
+
126
+ # Exchange code for tokens
127
+ tokens = self._exchange_code(code, redirect_uri, code_verifier)
128
+ self._tokens[scope] = tokens
129
+
130
+ return tokens.get("refresh_token", tokens["access_token"])
131
+
132
+ def _run_callback_server(self, auth_url: str, expected_state: str) -> str:
133
+ """Open browser and wait for OAuth callback. Returns authorization code."""
134
+ result: dict[str, str] = {}
135
+
136
+ class Handler(http.server.BaseHTTPRequestHandler):
137
+ def do_GET(self) -> None:
138
+ params = urllib.parse.parse_qs(
139
+ urllib.parse.urlparse(self.path).query
140
+ )
141
+ if "code" in params:
142
+ result["code"] = params["code"][0]
143
+ result["state"] = params.get("state", [""])[0]
144
+ if "error" in params:
145
+ result["error"] = params["error"][0]
146
+ result["error_description"] = params.get(
147
+ "error_description", [""]
148
+ )[0]
149
+ self.send_response(200)
150
+ self.send_header("Content-Type", "text/html")
151
+ self.end_headers()
152
+ self.wfile.write(
153
+ b"<h1>OK! You can close this window.</h1>"
154
+ )
155
+
156
+ def log_message(self, *args: Any) -> None:
157
+ pass # suppress logs
158
+
159
+ server = http.server.HTTPServer(
160
+ ("localhost", self._callback_port), Handler
161
+ )
162
+ webbrowser.open(auth_url)
163
+ server.handle_request()
164
+ server.server_close()
165
+
166
+ if "error" in result:
167
+ raise RuntimeError(
168
+ f"OAuth authorization failed: {result['error']} -- "
169
+ f"{result.get('error_description', '')}"
170
+ )
171
+ if "code" not in result:
172
+ raise RuntimeError("OAuth callback did not contain an authorization code.")
173
+ if result.get("state") != expected_state:
174
+ raise RuntimeError("OAuth state mismatch -- possible CSRF attack.")
175
+
176
+ return result["code"]
177
+
178
+ def _exchange_code(
179
+ self, code: str, redirect_uri: str, code_verifier: str
180
+ ) -> dict[str, Any]:
181
+ """Exchange authorization code for tokens."""
182
+ body = json.dumps({
183
+ "grant_type": "authorization_code",
184
+ "client_id": self._client_id,
185
+ "client_secret": self._client_secret,
186
+ "code": code,
187
+ "redirect_uri": redirect_uri,
188
+ "code_verifier": code_verifier,
189
+ }).encode()
190
+ req = urllib.request.Request(
191
+ self._token_url,
192
+ data=body,
193
+ headers={"Content-Type": "application/json"},
194
+ )
195
+ try:
196
+ resp = urllib.request.urlopen(req)
197
+ return json.loads(resp.read())
198
+ except Exception as exc:
199
+ read_fn = getattr(exc, "read", None)
200
+ detail = read_fn().decode() if read_fn and callable(read_fn) else str(exc)
201
+ raise RuntimeError(f"OAuth token exchange failed: {detail}") from exc
@@ -0,0 +1,57 @@
1
+ """OAuth credential provider for MCS.
2
+
3
+ A simple ``CredentialProvider`` that delegates to an ``AuthPort``
4
+ adapter (defaults to ``OAuthAdapter``). For direct OAuth access
5
+ without a Token Vault intermediary (e.g. Google API directly).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from typing import Any
12
+
13
+
14
+ class OAuthProvider:
15
+ """Credential provider using direct OAuth tokens.
16
+
17
+ Wraps an ``AuthPort`` adapter and caches the returned tokens.
18
+ Use this when you want to use OAuth tokens directly (no Auth0
19
+ Token Vault exchange).
20
+
21
+ Parameters
22
+ ----------
23
+ _auth :
24
+ Auth transport adapter satisfying ``AuthPort``. If not
25
+ provided, you must supply ``OAuthAdapter`` kwargs to build
26
+ one automatically.
27
+ **oauth_kwargs :
28
+ Keyword arguments forwarded to ``OAuthAdapter`` if ``_auth``
29
+ is not provided.
30
+ """
31
+
32
+ def __init__(self, *, _auth: Any | None = None, **oauth_kwargs: Any) -> None:
33
+ if _auth is not None:
34
+ self._auth = _auth
35
+ else:
36
+ from .oauth_adapter import OAuthAdapter
37
+ self._auth = OAuthAdapter(**oauth_kwargs)
38
+
39
+ # Cache: scope → (token, expires_at)
40
+ self._cache: dict[str, tuple[str, float]] = {}
41
+
42
+ def get_token(self, scope: str) -> str:
43
+ """Return a valid token for *scope* via OAuth.
44
+
45
+ Delegates to the ``AuthPort`` adapter and caches the result.
46
+ """
47
+ if scope in self._cache:
48
+ token, expires_at = self._cache[scope]
49
+ if time.time() < expires_at:
50
+ return token
51
+
52
+ token = self._auth.authenticate(scope)
53
+
54
+ # Cache for 50 minutes (typical OAuth token lifetime is 1 hour)
55
+ self._cache[scope] = (token, time.time() + 3000)
56
+
57
+ return token
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcs-auth-oauth
3
+ Version: 0.1.0
4
+ Summary: OAuth 2.0 Authorization Code adapter for the Model Context Standard.
5
+ Author-email: Danny Gerst <danny@dannygerst.de>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://www.modelcontextstandard.io
8
+ Project-URL: Source, https://github.com/modelcontextstandard/python-sdk
9
+ Keywords: mcs,modelcontextstandard,auth,oauth2,authorization-code
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: mcs-auth>=0.1
25
+ Dynamic: license-file
26
+
27
+ # mcs-auth-oauth
28
+
29
+ **Zero-dependency OAuth 2.0 for AI agents.** Authorization Code Flow with
30
+ PKCE for the **Model Context Standard (MCS)**.
31
+
32
+ No `requests`. No `authlib`. No heavyweight SDK. Just the Python standard
33
+ library, a 5-second localhost callback server, and your agent has an OAuth
34
+ token. Works with any OAuth 2.0 provider -- Google, Auth0, Microsoft,
35
+ GitHub, you name it.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install mcs-auth-oauth
41
+ ```
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ from mcs.auth.oauth import OAuthProvider
47
+
48
+ provider = OAuthProvider(
49
+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",
50
+ token_url="https://oauth2.googleapis.com/token",
51
+ client_id="...",
52
+ client_secret="...",
53
+ scopes={"gmail": "https://mail.google.com/"},
54
+ )
55
+
56
+ # Opens browser, user logs in, token returned
57
+ token = provider.get_token("gmail")
58
+ ```
59
+
60
+ ## How it works
61
+
62
+ 1. Agent calls `get_token("gmail")`
63
+ 2. Browser opens with the provider's consent screen
64
+ 3. User logs in and grants access
65
+ 4. Localhost callback receives the authorization code
66
+ 5. Code is exchanged for tokens (with PKCE)
67
+ 6. Token returned to agent -- done
68
+
69
+ The entire flow happens in a single `get_token()` call. The localhost
70
+ server lives for exactly one request and shuts down immediately.
71
+
72
+ ## Use with Auth0 Token Vault
73
+
74
+ ```python
75
+ from mcs.auth.auth0 import Auth0Provider
76
+ from mcs.auth.oauth import OAuthAdapter
77
+
78
+ provider = Auth0Provider(
79
+ domain="my-tenant.auth0.com",
80
+ client_id="...",
81
+ client_secret="...",
82
+ _auth=OAuthAdapter(
83
+ authorize_url="https://my-tenant.auth0.com/authorize",
84
+ token_url="https://my-tenant.auth0.com/oauth/token",
85
+ client_id="...",
86
+ client_secret="...",
87
+ extra_params={"connection": "google-oauth2", "audience": "..."},
88
+ ),
89
+ )
90
+ ```
91
+
92
+ ## Links
93
+
94
+ - **Homepage:** <https://www.modelcontextstandard.io>
95
+ - **Source:** <https://github.com/modelcontextstandard/python-sdk>
96
+
97
+ ## License
98
+
99
+ Apache-2.0
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/mcs/auth/oauth/__init__.py
5
+ src/mcs/auth/oauth/oauth_adapter.py
6
+ src/mcs/auth/oauth/oauth_provider.py
7
+ src/mcs_auth_oauth.egg-info/PKG-INFO
8
+ src/mcs_auth_oauth.egg-info/SOURCES.txt
9
+ src/mcs_auth_oauth.egg-info/dependency_links.txt
10
+ src/mcs_auth_oauth.egg-info/requires.txt
11
+ src/mcs_auth_oauth.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ mcs-auth>=0.1