Spaces:
Runtime error
Runtime error
File size: 9,776 Bytes
0887862 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | """
Google Forms MCP Tools
This module provides MCP tools for interacting with Google Forms API.
"""
import logging
import asyncio
from typing import Optional, Dict, Any
from auth.service_decorator import require_google_service
from core.server import server
from core.utils import handle_http_errors
logger = logging.getLogger(__name__)
@server.tool()
@handle_http_errors("create_form", service_type="forms")
@require_google_service("forms", "forms")
async def create_form(
service,
user_google_email: str,
title: str,
description: Optional[str] = None,
document_title: Optional[str] = None,
) -> str:
"""
Create a new form using the title given in the provided form message in the request.
Args:
user_google_email (str): The user's Google email address. Required.
title (str): The title of the form.
description (Optional[str]): The description of the form.
document_title (Optional[str]): The document title (shown in browser tab).
Returns:
str: Confirmation message with form ID and edit URL.
"""
logger.info(f"[create_form] Invoked. Email: '{user_google_email}', Title: {title}")
form_body: Dict[str, Any] = {"info": {"title": title}}
if description:
form_body["info"]["description"] = description
if document_title:
form_body["info"]["document_title"] = document_title
created_form = await asyncio.to_thread(
service.forms().create(body=form_body).execute
)
form_id = created_form.get("formId")
edit_url = f"https://docs.google.com/forms/d/{form_id}/edit"
responder_url = created_form.get(
"responderUri", f"https://docs.google.com/forms/d/{form_id}/viewform"
)
confirmation_message = f"Successfully created form '{created_form.get('info', {}).get('title', title)}' for {user_google_email}. Form ID: {form_id}. Edit URL: {edit_url}. Responder URL: {responder_url}"
logger.info(f"Form created successfully for {user_google_email}. ID: {form_id}")
return confirmation_message
@server.tool()
@handle_http_errors("get_form", is_read_only=True, service_type="forms")
@require_google_service("forms", "forms")
async def get_form(service, user_google_email: str, form_id: str) -> str:
"""
Get a form.
Args:
user_google_email (str): The user's Google email address. Required.
form_id (str): The ID of the form to retrieve.
Returns:
str: Form details including title, description, questions, and URLs.
"""
logger.info(f"[get_form] Invoked. Email: '{user_google_email}', Form ID: {form_id}")
form = await asyncio.to_thread(service.forms().get(formId=form_id).execute)
form_info = form.get("info", {})
title = form_info.get("title", "No Title")
description = form_info.get("description", "No Description")
document_title = form_info.get("documentTitle", title)
edit_url = f"https://docs.google.com/forms/d/{form_id}/edit"
responder_url = form.get(
"responderUri", f"https://docs.google.com/forms/d/{form_id}/viewform"
)
items = form.get("items", [])
questions_summary = []
for i, item in enumerate(items, 1):
item_title = item.get("title", f"Question {i}")
item_type = (
item.get("questionItem", {}).get("question", {}).get("required", False)
)
required_text = " (Required)" if item_type else ""
questions_summary.append(f" {i}. {item_title}{required_text}")
questions_text = (
"\n".join(questions_summary) if questions_summary else " No questions found"
)
result = f"""Form Details for {user_google_email}:
- Title: "{title}"
- Description: "{description}"
- Document Title: "{document_title}"
- Form ID: {form_id}
- Edit URL: {edit_url}
- Responder URL: {responder_url}
- Questions ({len(items)} total):
{questions_text}"""
logger.info(f"Successfully retrieved form for {user_google_email}. ID: {form_id}")
return result
@server.tool()
@handle_http_errors("set_publish_settings", service_type="forms")
@require_google_service("forms", "forms")
async def set_publish_settings(
service,
user_google_email: str,
form_id: str,
publish_as_template: bool = False,
require_authentication: bool = False,
) -> str:
"""
Updates the publish settings of a form.
Args:
user_google_email (str): The user's Google email address. Required.
form_id (str): The ID of the form to update publish settings for.
publish_as_template (bool): Whether to publish as a template. Defaults to False.
require_authentication (bool): Whether to require authentication to view/submit. Defaults to False.
Returns:
str: Confirmation message of the successful publish settings update.
"""
logger.info(
f"[set_publish_settings] Invoked. Email: '{user_google_email}', Form ID: {form_id}"
)
settings_body = {
"publishAsTemplate": publish_as_template,
"requireAuthentication": require_authentication,
}
await asyncio.to_thread(
service.forms().setPublishSettings(formId=form_id, body=settings_body).execute
)
confirmation_message = f"Successfully updated publish settings for form {form_id} for {user_google_email}. Publish as template: {publish_as_template}, Require authentication: {require_authentication}"
logger.info(
f"Publish settings updated successfully for {user_google_email}. Form ID: {form_id}"
)
return confirmation_message
@server.tool()
@handle_http_errors("get_form_response", is_read_only=True, service_type="forms")
@require_google_service("forms", "forms")
async def get_form_response(
service, user_google_email: str, form_id: str, response_id: str
) -> str:
"""
Get one response from the form.
Args:
user_google_email (str): The user's Google email address. Required.
form_id (str): The ID of the form.
response_id (str): The ID of the response to retrieve.
Returns:
str: Response details including answers and metadata.
"""
logger.info(
f"[get_form_response] Invoked. Email: '{user_google_email}', Form ID: {form_id}, Response ID: {response_id}"
)
response = await asyncio.to_thread(
service.forms().responses().get(formId=form_id, responseId=response_id).execute
)
response_id = response.get("responseId", "Unknown")
create_time = response.get("createTime", "Unknown")
last_submitted_time = response.get("lastSubmittedTime", "Unknown")
answers = response.get("answers", {})
answer_details = []
for question_id, answer_data in answers.items():
question_response = answer_data.get("textAnswers", {}).get("answers", [])
if question_response:
answer_text = ", ".join([ans.get("value", "") for ans in question_response])
answer_details.append(f" Question ID {question_id}: {answer_text}")
else:
answer_details.append(f" Question ID {question_id}: No answer provided")
answers_text = "\n".join(answer_details) if answer_details else " No answers found"
result = f"""Form Response Details for {user_google_email}:
- Form ID: {form_id}
- Response ID: {response_id}
- Created: {create_time}
- Last Submitted: {last_submitted_time}
- Answers:
{answers_text}"""
logger.info(
f"Successfully retrieved response for {user_google_email}. Response ID: {response_id}"
)
return result
@server.tool()
@handle_http_errors("list_form_responses", is_read_only=True, service_type="forms")
@require_google_service("forms", "forms")
async def list_form_responses(
service,
user_google_email: str,
form_id: str,
page_size: int = 10,
page_token: Optional[str] = None,
) -> str:
"""
List a form's responses.
Args:
user_google_email (str): The user's Google email address. Required.
form_id (str): The ID of the form.
page_size (int): Maximum number of responses to return. Defaults to 10.
page_token (Optional[str]): Token for retrieving next page of results.
Returns:
str: List of responses with basic details and pagination info.
"""
logger.info(
f"[list_form_responses] Invoked. Email: '{user_google_email}', Form ID: {form_id}"
)
params = {"formId": form_id, "pageSize": page_size}
if page_token:
params["pageToken"] = page_token
responses_result = await asyncio.to_thread(
service.forms().responses().list(**params).execute
)
responses = responses_result.get("responses", [])
next_page_token = responses_result.get("nextPageToken")
if not responses:
return f"No responses found for form {form_id} for {user_google_email}."
response_details = []
for i, response in enumerate(responses, 1):
response_id = response.get("responseId", "Unknown")
create_time = response.get("createTime", "Unknown")
last_submitted_time = response.get("lastSubmittedTime", "Unknown")
answers_count = len(response.get("answers", {}))
response_details.append(
f" {i}. Response ID: {response_id} | Created: {create_time} | Last Submitted: {last_submitted_time} | Answers: {answers_count}"
)
pagination_info = (
f"\nNext page token: {next_page_token}"
if next_page_token
else "\nNo more pages."
)
result = f"""Form Responses for {user_google_email}:
- Form ID: {form_id}
- Total responses returned: {len(responses)}
- Responses:
{chr(10).join(response_details)}{pagination_info}"""
logger.info(
f"Successfully retrieved {len(responses)} responses for {user_google_email}. Form ID: {form_id}"
)
return result
|